Sending complex JSON objects to Asp.net MVC using jQuery
I'm defining an object like:
data = {
first: { Id: 1, Name: "This is my fir开发者_运维知识库st name." },
second: { Id: 2, Name: "The second one." }
};
Then I'm trying to issue an Ajax request using:
$.ajax({
url: "/SomeURL"
type: "POST",
data: data,
success: function(){ ... },
error: function(){ ... }
});
But my data gets converted into an array like structure that Asp.net MVC default model binder isn't able to grasp.
first[Id]=1&first[Name]=...
What should I set or do, so jQuery will correctly convert these into:
first.Id=1&first.Name=...
Have you tried flattening your data?
data = {
"first.Id": 1,
"first.Name": "This is my first name.",
"second.Id": 2,
"second.Name": "The second one."
};
Here's a little jQuery extension to flatten your data:
jQuery.flatten = function(data) {
var flattenFunc = function(flattenedData, flattenFunc, name, value) {
if (typeof(value) == 'object') {
for (var item in value) {
flattenFunc(flattenedData, flattenFunc, name ? name + '.' + item : item, value[item]);
}
}
else {
flattenedData[name] = value;
}
};
var flattenedData = new Array();
flattenFunc(flattenedData, flattenFunc, null, data);
return flattenedData;
};
Simply replace data
with $.flatten(data)
in your Ajax request.
How about trying JSON ?
- http://blogs.msdn.com/b/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx
- https://github.com/douglascrockford/JSON-js
- http://www.json.org/
You can create a function to make your N levels json to a 1 level json like this:
$.simplifyJson = function(startingJson) {
var fn = function(startingJson, parentKey) {
var result = {};
for(key in startingJson) {
var newKey = parentKey;
if(newKey != "")
newKey += ".";
newKey += key;
if(typeof(startingJson[key]) == "object") {
var result2 = fn(startingJson[key], newKey);
for(key2 in result2) {
result[key2] = result2[key2];
}
}
else {
result[newKey] = startingJson[key];
}
}
return result;
};
return fn(startingJson, "");
}
So when you do this:
var startingJson = {
a: "hola",
b: {
c: "chau",
d: "chau2"
}
};
var endingJson = $.simplifyJson(startingJson);
In endingJson
you will get this
{
a: "hola",
b.c: "chau",
b.d: "chau2"
}
Here is an example: http://jsfiddle.net/bY9nD/2/
Javascript
var access = {
Id: 0,
HotelId: dropdownlistAccess.value(),
RoleId: dropdownlistRole.value(),
User: {
Email: email
}
};
$.ajax({
url: "Access/Add",
cache: false,
type: "POST",
contentType: 'application/json',
data: JSON.stringify(access),
success: function () {
refreshDataSource();
}
});
Working for Controller Action
public ActionResult Add(AccessViewModel newAccessViewModel)
{
// Your code here...
}
The AccessViewModel & UserViewModel field
public partial class AccessViewModel
{
[Required(ErrorMessage="Id is required")]
public int Id { get; set; }
[Required(ErrorMessage="UserId is required")]
public int UserId { get; set; }
[Required(ErrorMessage="HotelId is required")]
public int HotelId { get; set; }
[Required(ErrorMessage="RoleId is required")]
public int RoleId { get; set; }
public UserViewModel User { get; set; }
}
public partial class UserViewModel
{
[Required(ErrorMessage="Id is required")]
public int Id { get; set; }
[Required(ErrorMessage="Email is required")]
[StringLength(50)]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
精彩评论