Where To Put Custom Object Formatter In MVC Application
Jan 12, 2011
I'm teaching myself ASP.NET MVC, and am trying to figure out where best to put a function which takes in an Models.Address instance and returns an IHtmlString instance which reads something like:
Line 1<br />
Line 2<br />
City, State
The string could be used in many places throughout my project, so I don't want to write it in one view and have to keep copy-pasting it or attaching that view: By the same logic attaching it to ViewData seems like a bad idea. However, the HtmlEncode method requires an instance of server, which means I can't add the function to the model class either.
Is there a right place to put this - some sort of shared view? (does this belong in the master?) Or am I going about this all wrong?
My current best idea is to create a ViewModel with the method public IHtmlString FormatAddress(Address address, HttpServerUtility server), but I don't know if that's the ASP.NET MVC way to do it.
View 2 Replies
Similar Messages:
Apr 13, 2010
I'm writing messages to a Message Queue in C# as follows:
ObjectMsg objMsg = new ObjMsg(1,"ascii",20090807);
Message m = new Message();
m.Formatter = new BinaryMessageFormatter();
m.body = objMsg;
queue.Send(m);
and I'm trying to read the messages as follows:
Message m = new Message()
m.Formatter = new BinaryMessageFormatter();
MessageQueue mq = new MessageQueue("./pqueue");
m = mq.Recieve();
ObjMsg msg = (ObjMsg )m.Body;
However I'm getting an error message which says: "Cannot find a formatter capable of reading this message."
View 1 Replies
Aug 30, 2010
I've scenario where I want to insert data into database without post back. there are around 12 to 13 fields which i need to insert. I'm passing DTO from the client side which is actually Json object. Now the problem which i'm facing is how to convert that Json object which i got in webservice to the "class" (in my case class name is User) object.
[Code]....
In the above case AddNewUser method takes the object of User class. But i'm getting casting error. So how do I convert Json object to the "User" class object?
View 3 Replies
Sep 29, 2010
I have the following code:
[WebMethod]
[SoapHeader("_webServiceAuth")]
public User GetUser(string username){
try
{
this._validationMethods.Validate(_webServiceAuth);
User user = new User(username);
[code]...
View 1 Replies
Mar 23, 2010
What I'm trying to do is rather basic, but I might have my facts mixed up. I have a details page that has a custom class as it's Model. The custom class uses 2 custom objects with yet another custom object a property of one of the 2. The details page outputs a fair amount of information, but allows the user to post a comment. When the user clicks the post button, the page gets posted to a Details action that looks something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Details(VideoDetailModel vidAndComment) { ....}
[Code]....
The only fields on the form that is posted are CommentText and VideoId. Here is what the VideoDetailModel looks like.
public class VideoDetailModel
{
public VideoDetailModel()
{
[Code]....
I suppose if I added more form fields for the properties I need, they would get posted, but I only need 1 form entry field for the CommentText. If I could get the same Model objects value that were sent to the page to post with the page, it looks like the solution is rather simple. I think using the RenderPartial in the middle of a form is problematic somehow to how the form gets written in html. I can't really put my finger on why things went bonkers, but if I do my RenderPartials before my form and then begin my form with the text entry field and the hidden VideoId, the default ModelBinder works just fine. I was beginning the form, writing the hidden VideoId, rendering several partial views, create my CommentText field, and then closed the form out. The CommentText field would get bound just fine. The hidden VideoId would not. Maybe I missed a rule somewhere about using RenderPartial.
For completeness, the partial view I was rendering took a Comment object and just wrote out it's CommentText data. Several of these objects would exist for a single Video object. All of this data was in a custom type and passed into the View (the main view) as it's Model. This partial view did not have a form and did not have any data entry fields.
View 2 Replies
Dec 27, 2010
I have Create a Custom Principal and a Custom Identiy for my Web Application and upon forms authentication
1 Create a profile of type object
2 Assign it to the Principal profile
3 assign the principal to the Http.Current.User (this now has the complete profile information )
As i understand upon redirection the principal is recreated and i loose the information i had stored in the profile.
I there a way to persist the profile information ?
I though can achieve persisting some information using FormsAuthenticationTicket in userData but that wouldent solve my purpose ..
View 7 Replies
Sep 9, 2010
I have
[ServiceContract]
public interface IBusiness
{
[OperationContract][code]....
Add client: [Code]....
But......... the result
Error:The server encountered an error processing the request. The exception message is 'The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'UpdateLanguage'. The token '"' was expected
but found '''.'. See server logs for more details. The exception stack trace is:
at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest
View 1 Replies
Apr 16, 2010
I have created my custom MembershipProvider. I have used an instance of the class DBConnect within this provider to handle database functions. Please look at the code below:
public class SGIMembershipProvider : MembershipProvider
{
#region "[ Property Variables ]"
private int newPasswordLength = 8;
private string connectionString;
private string applicationName;
private bool enablePasswordReset;
private bool enablePasswordRetrieval;
private bool requiresQuestionAndAnswer;
private bool requiresUniqueEmail;
private int maxInvalidPasswordAttempts;
private int passwordAttemptWindow;
private MembershipPasswordFormat passwordFormat;
private int minRequiredNonAlphanumericCharacters;
private int minRequiredPasswordLength;
private string passwordStrengthRegularExpression;
private MachineKeySection machineKey;
**private DBConnect dbConn;**
#endregion
.......
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
if (!ValidateUser(username, oldPassword))
return false;
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
{
throw args.FailureInformation;
}
else
{
throw new Exception("Change password canceled due to new password validation failure.");
}
}
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@applicationName", applicationName);
p[1] = new SqlParameter("@username", username);
p[2] = new SqlParameter("@password", EncodePassword(newPassword));
bool retval = **dbConn.ExecuteSP("User_ChangePassword", p);**
return retval;
} //ChangePassword
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
......
ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
if ((ConnectionStringSettings == null) || (ConnectionStringSettings.ConnectionString.Trim() == String.Empty))
{
throw new ProviderException("Connection string cannot be blank.");
}
connectionString = ConnectionStringSettings.ConnectionString;
**dbConn = new DBConnect(connectionString);
dbConn.ConnectToDB();**
......
} //Initialize
......
} // SGIMembershipProvider
I have instantiated dbConn object within Initialize() event. My problem is that how could i dispose off this object when object of SGIMembershipProvider is disposed off. I know the GC will do this all for me, but I need to explicitly dispose off that object. Even I tried to override Finalize() but there is no such overridable method. I have also tried to create destructor for SGIMembershipProvider.
View 2 Replies
Feb 9, 2011
We have a custom web app built using Ektron v8.0 which uses EL 3.1 and the format template in the logging config is configured as such:
<add
name="Text Formatter"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
template="Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Extended Properties: {dictionary({key} - {value}
)}"
/>
Is there a template item for Request URL? Without the request url with querystring parameters, it's difficult to debug errors.
View 1 Replies
Feb 11, 2010
Is there an easy way to populate my C# Object with the JSON object passed via AJAX?
//This is the JSON Object passed to C# WEBMETHOD from the page using JSON.stringify
{"user":{"name":"asdf","teamname":"b","email":"c","players":["1","2"]}}
//C# WebMetod That receives the JSON Object
[WebMethod]
public static void SaveTeam(Object user)
{
}
//C# Class that represents the object structure of JSON Object passed in to the WebMethod
public class User
{
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
View 4 Replies
Jul 17, 2010
I am trying to run the 15 minutes movies MVC application but I got the following error:
Object reference not set to an instance of an object.
Description:
An unhandled exception occurred during the execution of the current web request. review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
[Code]....
View 1 Replies
Jul 13, 2010
I have to implement broker and dealer socket connection like in share market i.e. it should connect at 9 AM and stop at 3.30 PM and repeat in next morning ...
so following is my requirement
1) i have to create application object once in day at 9 AM and destroyed at particular end day 3.30 PM.
My question is how to destroyed application object at given particular time ... i think this can be done in application_end handler in global.asax ... but my question is when no request is made at that time then what happened..
View 2 Replies
Apr 1, 2011
If I have the following ASP.NET code (it's not complete - obviously there's a lot missing, but none of it matters):
<asp:GridView>
<Columns>
<asp:TemplateField>
<ItemTemplate>
My Label: <asp:Label />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
My Text Box: <asp:TextBox />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And if I have something like this in the CodeBehind:
Private MyListOfObjects As List(Of MyObject)
...
Public Class MyObject
Public MyTextBoxString as String
Public MyLabelString as String
End Class
How can I bind the GridView so that one row is equivalent to one item in my MyListOfObjects list, and so that the data will populate and persist across page loads or postbacks? I've never done custom databinding like this before. All the tutorials I've come across so far only talk about using GridViews directly with Database query results, and that's not what I need.
View 4 Replies
Mar 23, 2011
I've implemented a custom ASP.net membership provider to deal with forms authentication. The custom provider uses a custom User object for authentication and authorization. I was wondering If I can pass this object to each WCF call without adding it to the parameters list?
View 2 Replies
Jul 11, 2010
I'm using DropDownList within my WebApplication. I need to keep additional piece of information with each Item on list. How can I achieve this?
View 3 Replies
Aug 4, 2010
I am wondering how I am supposed to get/set/replace the ImageUrl using asp
[Code]....
Where it says GetImage, I want to get the string of the url path which is stored in a List of custom objects that gets binded to the gridview...
View 1 Replies
Sep 14, 2010
For my ASP.Net application I need to use a HTTP REST API that returns a JSON object.Here's how the JSON looks:
message: [
{
type: "message"
href: "/messages/id/23"[code]....
I could use the DataContractJsonSerializer Class and have custom Classes defined. However, am not sure how keys like "$" would get converted to in .Net.
View 3 Replies
Jan 6, 2010
[Code]....
Isnt it possible to shorten this method? What i would like to know if its possible to just do something like
bestItem[enumerator.Key] = enumerator.Value.ToString();
View 1 Replies
Nov 29, 2010
I'd like to add some custom instance properties to an ASP.Net User object. for example, I'd like to log every user's login and have something like: User.LoginTimes or calculate the User Profile's Completion percentage and be able to access it like: User.ProfileInfoPercentage, etc.
Now What I'd like to know is what would be the best approach to do this?
Forget about user instances? (e.g. define a database table with userid and ProfilePercentage info and retrieve data from profile like: DB.GetProfilePercentage(Context.Current.User.UserID) )
Override the ASP.Net User class and add my own functionalities.
Use Extension methods for the user class.
View 1 Replies
Feb 11, 2010
I'm kinda new to web services and want to make sure I am doing things correctly.
I have a custom object which has sub objects as well. (let's say Company object, sub object is collection of Employee objects)
I want the web service to return a collection of Company objects. Do I make the service return a Dataset and custom generate a dataset with datatables representing the different objects?
What is the best way to do this? I tried to just serialize it, but that doesn't seem to work either.
I tried this dll
[URL]
But the output XML doesn't seem to include the sub object.
View 1 Replies
Jan 2, 2011
In my controller I fetch a list of object 'object1' which has two fields field1 & field2.Now I have a model model1 which has two fields fieldsX & fieldY.fieldX = field1fieldY = dosomething(field2 also have a view model ViewModel1 which has a single fieldpublic List<model1> model2I need to send model2 to my view
View 4 Replies
Aug 7, 2010
How do I store a variable or object application wide in ASP.net MVC. In regular ASP, you had the Application object, and in ASP.net too apparently.
View 1 Replies
Dec 28, 2010
Using C#, ODP.NET and ASP.NET Web Services:
ClassA is a custom class generated from a "type" in oracle database.
ClassB is a custom class generated from a "table of type ClassA" in Oracle database.
The exposed service includes a login procedure which gets a username as input parameter and returns object B. Debugging the login procedure I can see that the data is retrieved from the database but not printed in the wsdl..
[Code]....
My ClassB definition is as follows:
[XmlInclude(typeof(ClassB))]
public class ClassB : INullable, IOracleCustomType, IXmlSerializable
...
similar definition holds for ClassA as well. the generated wsdl is :
<? xml version="1.0" encoding="utf-8" ?>
<ClassB xmlns="http://tempuri/org" />
and no data printed out. What may be the problem?
View 3 Replies
Jul 19, 2010
I want to sort my gridview binded to an object datasource fetching business objects. I have already implemented custom paging & now want to implement sorting. Just read this article but there is lot of concatenation going on there with the SQL Query.
[URL]
View 2 Replies
May 11, 2010
I have a custom class declared as follows (in vb.net)
<Serializable()> _
Public Class NumInfo
Public n As String
Public f As Integer
Public fc As char()
Public t As Integer
Public tc As char()
Private validFlag As Boolean = True
Public Sub New()
End Sub
I also have public properties(read/write) for all the public variables
End Class
In my service.asmx codebehind class I have a webmethod as follows:
<WebMethod> _
<XmlInclude(GetType(NumInfo))>
Public Function ConvertTo(ByVal info As NumInfo) As String
Return mbc(info)
'mbc is another function defined in my service.asmx "service" class
End Function
The problem is that when I start debugging it to test it, the page that I get does not contain any fields where I could input the values for the public fields of numInfo. How do I initialise the class? There is no "Invoke" button either. All I see are soap details as below:
ConvertTo
Test
The test form is only available for methods with primitive types as parameters. SOAP 1.1 The following is a sample SOAP 1.1 request and response. The placeholders shown need to be replaced with actual values.
POST /BaseConverter/BaseCon.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://RohitServices.in/ConvertTo"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ConvertTo xmlns="http://RohitServices.in/">
<info>
<n>string</n>
<f>int</f>
<fc>
<char>char</char>
<char>char</char>
</fc>
What am I doing wrong? For the record I tried replacing char() with string to see if it was the array causing problems but that didn't help either. I'm fairly new to web services. I tried replacing the custom object parameter with a primitive parameter just to check how things worked and it rendered a page with an input field and invoke button. I just can't seem to get it working with custom object.
View 2 Replies