ASP.NET MVC How to pass JSON object from View to Controller as Parameter - asp.net-mvc

I have a complex JSON object which is sent to the View without any issues (as shown below) but I cannot work out how Serialize this data back to a .NET object when it is passed back to the controller through an AJAX call. Details of the various parts are below.
var ObjectA = {
"Name": 1,
"Starting": new Date(1221644506800),
"Timeline": [
{
"StartTime": new Date(1221644506800),
"GoesFor": 200
}
,
{
"StartTime": new Date(1221644506800),
"GoesFor": 100
}
]
};
I am not sure how this object can be passed to a Controller Method, I have this method below where the Timelines object mirrors the above JS object using Properties.
public JsonResult Save(Timelines person)
The jQuery I am using is:
var encoded = $.toJSON(SessionSchedule);
$.ajax({
url: "/Timeline/Save",
type: "POST",
dataType: 'json',
data: encoded,
contentType: "application/json; charset=utf-8",
beforeSend: function() { $("#saveStatus").html("Saving").show(); },
success: function(result) {
alert(result.Result);
$("#saveStatus").html(result.Result).show();
}
});
I have seen this question which is similar, but not quite the same as I am not using a forms to manipulate the data.
How to pass complex type using json to ASP.NET MVC controller
I have also seen references to using a 'JsonFilter' to manually deserialize the JSON, but was wondering if there is a way to do it nativly though ASP.NET MVC? Or what are the best practices for passing data in this way?

Edit:
This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
You can use this ObjectFilter:
public class ObjectFilter : ActionFilterAttribute {
public string Param { get; set; }
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
object o =
new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
}
}
}
You can then apply it to your controller methods like so:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.

You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.
$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:
Data to be sent to the server. It is
converted to a query string, if not
already a string. It's appended to the
url for GET-requests. See processData
option to prevent this automatic
processing. Object must be Key/Value
pairs. If value is an Array, jQuery
serializes multiple values with same
key i.e. {foo:["bar1", "bar2"]}
becomes '&foo=bar1&foo=bar2'.
Therefore:
You aren't passing JSON to the server. You're passing JSON to jQuery.
Model binding happens in the same way it happens in any other case.

A different take with a simple jQuery plugin
Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.
This plugin supports dates just as well, so they get converted to their DateTime counterpart without a problem.
You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.
All you have to do is to use this plugin on the client side. An Ajax request would look like this:
$.ajax({
type: "POST",
url: "SomeURL",
data: $.toDictionary(yourComplexJSONobject),
success: function() { ... },
error: function() { ... }
});
But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error function would get called as it's supposed to be.

There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject method that just makes a plain object. You can then use reflection to get at the properties you need.
If your controller takes a FormCollection, and you didn't add anything else to the data the json should be in form[0]:
public ActionResult Save(FormCollection forms) {
string json = forms[0];
// do your thing here.
}

This answer is a follow up to DaRKoN_'s answer that utilized the object filter:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.
What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:
public class SomeViewModel()
{
public Person Person { get; set; }
public Address Address { get; set; }
}
Then I would bind the view to SomeViewModel. You can do the same thing with JSON.
[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
Person p = jsonViewModel.Person;
Address a = jsonViewModel.Address;
// Do stuff
jsonViewModel.Person = p;
jsonViewModel.Address = a;
return Json(jsonViewModel);
}
Then in the view you can use a simple call with JQuery like this:
var json = {
Person: { Name: "John Doe", Sex: "Male", Age: 23 },
Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};
$.ajax({
url: 'home/doJsonStuff',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json), //You'll need to reference json2.js
success: function (response)
{
var person = response.Person;
var address = response.Address;
}
});

in response to Dan's comment above:
I am using this method to implement
the same thing, but for some reason I
am getting an exception on the
ReadObject method: "Expecting element
'root' from namespace ''.. Encountered
'None' with name '', namespace ''."
Any ideas why? – Dan Appleyard Apr 6
'10 at 17:57
I had the same problem (MVC 3 build 3.0.11209.0), and the post below solved it for me. Basically the json serializer is trying to read a stream which is not at the beginning, so repositioning the stream to 0 'fixed' it...
http://nali.org/asp-net-mvc-expecting-element-root-from-namespace-encountered-none-with-name-namespace/

Related

JSON.Stringify ASP.NET MVC

I am trying to post data in JSON format to a .NET MVC Controller like this.
$.ajax({
type: 'POST',
url: 'http://mvc.tester.local/Home/NameConverter',
data: JSON.stringify({ convertermodel.InputName: obj.currentTarget.value }),
contentType: 'application/json'
});
But Javascript complains about the JSON.Stringify() bit.
The convertermodel.InputName to be exact.
The thing is I actually need this JSON data name to be that way i.e. have the same name as a property in my model; in order to take advantage of reflection for automatic binding.
This is my model:
public class NamesViewModel
{
public NameConverterModel convertermodel = new NameConverterModel();
}
and the sub Class
public class NameConverterModel
{
private string _inputName = "";
public string InputName
{
get { return _inputName; }
set { _inputName = value; }
}
}
How can I solve this please ?
I hope I am clear enough.
You would need your JSON to be of the structure like this:
{"convertermodel" : {
"InputName" : obj.currentTarget.value
}
}
Your JSON representation of your object needs to reflect the appropriate nesting that your object model that you're trying to model in the client-side requires. So defining your JSON by nesting your hierarchy at one level won't work -- you need to create objects of objects like you did in your C# code.

How can I pass a list of objects to an ASP.NET MVC action using jQuery?

I have defined an object type in .NET that I want receive in a List<> as the input to an ASP.NET MVC action method?
Here is the action method and class I'm trying to receive.
public class WhereClause
{
public string ColumnInformation { get; set; }
public string WhereValue { get; set; }
public string AndOr { get; set; }
public string Comparer { get; set; }
}
public ActionResult Grid(string query, int skip = 0, int take = 50, List<WhereClause> whereClauses = null)
{
GridViewModel gvm = new GridViewModel();
gvm.Query = query;
And here is the Javascript where I'm building up the collection from a set of table rows using jQuery and then calling the jQuery ajax() method.
var whereClauses = [];
// Iterate over every row in the table and pull the values fromthe cells.
divQueryWidget.find('.tblWhereClauses tr').each(function (x, y) {
var tds = $(y).find('td');
var columnInformation = $(tds[0]).html();
var whereValue = $(tds[1]).html();
var andOr = $(tds[2]).html();
var comparer = $(tds[4]).html();
// Create a whereClause object
var whereClause = {};
whereClause.ColumnInformation = columnInformation;
whereClause.WhereValue = whereValue;
whereClause.AndOr = andOr;
whereClause.Comparer = comparer;
whereClauses.push({
ColumnInformation: columnInformation,
WhereValue: whereValue,
AndOr: andOr,
Comparer: comparer
});
});
//divQueryWidget.find('#queryResultsGrid').
$.ajax({
type: 'GET',
url: '<%= Url.Action("Grid", "Query") %>',
dataType: 'html',
data: { query: divQueryWidget.find('#activeQuery').val(), whereClauses: whereClauses },
success: function (data, textStatus, XMLHttpRequest) { divQueryWidget.find('#queryResultsGrid').append(data); divQueryWidget.find('.loading').css('visibility', 'hidden'); }
});
Here is where things get interesting. When the javascript is called and there were two rows in the table that are supposed to be passed to the MVC action, notice how when I debug into the code that there were two objects created in the list but their properties weren't filled.
What am I doing wrong that is preventing my Javascript object from being converted into a .NET List<> type? Should I be using array? Do I need to mark something as serializable?
i'd be interested in the results. i never tried to post such big chuncks of data with jQuery Ajax, but i guess it should be possible.
i think the problem here is about the labels.
when you make a List<> of items, in a normal view, with a foreach loop for example, the labels of the values have keys. you are missing those keys, and i think thats why it doesnt work.
for example, i have a List which i make with jQuery, but send in a normal postback.
in the FormCollection object i get the following keys
[0] "Vrbl_Titel" string
[1] "Sch_ID" string
[2] "Vragen[0].Evvr_Vraag" string
[3] "Vragen[0].Evvr_Type" string
[4] "Vragen[1].Evvr_Vraag" string
[5] "Vragen[1].Evvr_Type" string
[6] "Vragen[2].Evvr_Vraag" string
[7] "Vragen[2].Evvr_Type" string
a Vragen object has 2 strings, as you can see, so this is how it looks, and i guess this is how you have to make it in jQuery, before posting it to the server.
be careful though, the integer between the brackets should be without interruption. if you have an interruption (for example, 0 1 2 4 5 6) then MVC will stop at 2.
It might have something to do with the name of the fields of the objects being enclosed in parentheses when sent by Jquery (you can confirm this in Firebug).

What is the proper way to do multi-parameter AJAX form validation with jQuery and ASP.NET MVC?

I have a registration form for a website that needs to check if an email address already exists for a given company id. When the user tabs or clicks out of the email field (blur event), I want jQuery to go off and do an AJAX request so I can then warn the user they need to pick another address.
In my controller, I have a method such as this:
public JsonResult IsEmailValid(int companyId, string customerNumber)
{
return Json(...);
}
To make this work, I will need to update my routes to point directly to /Home/IsEmailValid and the two parameters {companyId} and {customerNumber}. This seems like I'm "hacking" around in the routing system and I'm guessing perhaps there is a cleaner alternative.
Is there a "proper" or recommended way to accomplish this task?
EDIT: What I meant by the routes is that passing in extra parameter ({customerNumber}) in the URL (/Home/IsEmailValid/{companyId}/{customerNumber}) won't work with the default route mapping.
You can use the jQuery Validation Plugin to do that.
You're gonna have to implement your own method though like this :
$.validator.addMethod("checkCompanyEmail", function(value, element) {
var email = value;
var companyID = //get the companyID
var result;
//post the data to server side and process the result and return it
return result;
}, "That company email is already taken.");
Then register your validation method :
$("#the-form").validate({
rules: { email: { required: true, "checkCompanyEmail" : true } }
});
PS. I don't understand why you need to "hack around" with routing for that.
from the validate documentation under remote method
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $("#username").val();
}
}
}

Json isn't returning a result that is accessible as an array

I'm having troubles reading a Json result back from a controller method...
I have this method in my controller:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetCurrent()
{
IList<string> profile = new List<string>();
profile.Add("-1");
profile.Add("Test");
profile.Add("");
return this.Json(profile);
}
And it is being called by this jquery ajax post:
$.post("/Profile/GetCurrent", function(profile) { profileCompleteOpen(profile); }, "json");
and the javascript function called on the post's callback:
function profileCompleteOpen(profile) {
alert(profile);
alert(profile[0]);
}
The result of the first alert shows the array like this:
["-1","Test",""]
But the result of the second alert shows this:
[
rather than
-1
What am I doing wrong here... I've compared it to one of the other times I'm doing this and it seems to be the exact same. Why isn't it recognizing it's an array?
Thanks,
Matt
Try converting the json data in profile to a proper object by using eval() on it.
Example:
var profileObject = eval('(' + profile + ')');
Hmmm, I'd be doing what you're trying to do a little differently.
I'd either return a fully qualified object and then use it's properties;
class MyObj
{
public string name{get;set;}
}
fill the object and return it as a json object. then you're jquery code can access like any other object.
The other way might be to do a return PartialView("MyView", model);
That will return the partial view as html back to your page which you can then append to your html.
I think the type of profile is string instead of array. Why? Check the $.post method parameters. Maybe the problem is there.
$.post("url", null, function(profile) { ... }, "json");

Post multiple parameters to MVC Controller using jQuery.post

I have a controller defined as:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult PostMoreData(DataContracts.Address address, DataContracts.GeoLocation geoLocation)
{
return Json("test");
}
where DataContracts.Address and DataContracts.GeoLocation are complex types.
From my View i'm trying to post using jQuery as such:
function PostMoreData() {
var JsonAddress = {
"Building": $('Building').val(),
"UnitNumber": $('UnitNumber').val(),
"StreetNumber": $('StreetNumber').val(),
"StreetName": $('StreetName').val(),
"StreetType": $('StreetType').val(),
"Suburb": $('Suburb').val(),
"State": $('State').val(),
"Postcode": $('Postcode').val(),
"MonthsAtAddress": $('MonthsAtAddress').val()
};
var JsonGeoLocation = {
"Latitude": $('Latitude').val(),
"Longitude": $('Longitude').val()
};
jQuery.post("/AddressValidation/PostMoreData", {address: JsonAddress, geoLocation: JsonGeoLocation}, function(data, textStatus) {
if (textStatus == "success") {
var result = eval(data);
if (result.length > 0) {
alert(result);
}
}
}, "json");
}
However, on the controller, I get nulls.
It works if my Controller takes just 1 argument and I post just one object.
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult PostMoreData(DataContracts.Address address)
{
return Json("test");
}
function PostMoreData() {
var JsonAddress = {
"Building": $('Building').val(),
"UnitNumber": $('UnitNumber').val(),
"StreetNumber": $('StreetNumber').val(),
"StreetName": $('StreetName').val(),
"StreetType": $('StreetType').val(),
"Suburb": $('Suburb').val(),
"State": $('State').val(),
"Postcode": $('Postcode').val(),
"MonthsAtAddress": $('MonthsAtAddress').val()
};
jQuery.post("/AddressValidation/PostMoreData", JsonAddress, function(data, textStatus) {
if (textStatus == "success") {
var result = eval(data);
if (result.length > 0) {
alert(result);
}
}
}, "json");
}
Any ideas how i can post more than one object?
Note that the "default serialization" that jQuery is doing here isn't going to work no matter what your controller does. jQuery doesn't "traverse" the parameter map below the first level, so the example in the question is likely generating this post data:
address=[object]&geoLocation=[object]
The other, working example does not contain any sub-objects, so it is being translated directly, like this:
Building=value&UnitNumber=value&...&MonthsAtAddress=value
The easiest fix is making the parameter map flat, each key prefixed with either 'Address.' or 'GeoLocation.', depending.
Thank you everyone for your input on this issue.
At this stage, we have departed from using jquery to post complex types to controllers. Instead we use the ms ajax framework to do that. ms ajax post nicely binds the complex types automatically out of the box.
So our solution now uses a mix of jquery and ms ajax framework.
Ash
Your code requires that the way jquery serializes an object is compatible with the MVC default model binder, which I think is unlikely.
If you can build your javascript object so that it serializes as a flat object with dot notation (JsonAddress.Building) that would work, or you can let jquery do the default serialization and then create a custom model binder to deserialize to the action parameter types.
I had the same problem and couldn't get anything to work. Also someone raised it as a bug with jquery and they closed it as not a bug.
I have found a few solutions which answer part of the whole question.
And the answer includes the following.
1) Client side: we would need to stringyfy all the objects you need to send. This could be a normal object or an array. It works on both.
2) Client side: You send the data as you have in the first post. As you would object by object.
Tip: When you send parameterised objects, jquery encodes the data sent to the server.
Following all are server side implementations
1) Deserializer class: which will take the input string and put it back in to object/list<>/IList<> what ever you have defined as datatype of the parameter of the controller function.
You would need to implement ActionFilterAttribute for the above.
2) Finally add an attribute to controller function, so that it uses the deserialiser class to get the parameters.
As this is quite a lot of code let me know if you need details or have you solved the problem.
Deepak Chawla

Resources