使用jQuery异步传递含复杂属性及集合属性的Model到控制器方法
时间:2014-05-14 12:49:24
收藏:0
阅读:351
Student类有集合属性Courses,如何把Student连同集合属性Courses传递给控制器方法?
public class Student
{
public string StudentName { get;
set; }
public
IList<Course> Courses { get; set; }
}
public class Course
{
public string CourseName { get;
set; }
}
□ 思路
在前端拼装成与Student吻合、对应的对象,再使用JSON.stringify()或$.toJSON()方法转换成json格式传递给控制器方法,使用$.toJSON()方法需要引用一个jQuery的扩展js文件。
□ Home/Index.cshtml
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml";}
<a id="btn" href="javascript:void(0)">走你</a>
@section scripts
{ <script src="~/Scripts/json.js"></script> <script type="text/javascript"> $(function () { $(‘#btn‘).click(function() {var arr = [];
var obj1 = new Object(); obj1.CourseName = "语文";arr.push(obj1);
var obj2 = new Object(); obj2.CourseName = "数学";arr.push(obj2);
var student = { StudentName: ‘小明‘,Courses: arr
};
//var json = JSON.stringify(student);var json = $.toJSON(student);
$.ajax({ url: ‘@Url.Action("GetStuent","Home")‘, type: ‘POST‘, contentType: ‘application/json; charset=utf-8‘,data: json,
dataType: ‘json‘, success: function (data) {alert(data.StudentName);
for (i = 0; i < data.Courses.length; i++) {alert(data.Courses[i].CourseName);
}
}
});
});
});
</script>
}
□ HomeController
public ActionResult Index() { return View();}
[HttpPost]
public ActionResult GetStuent(Student student) { return Json(student);}
□ 把对象转换成json格式的jQuery扩展
// From: http://www.overset.com/2008/04/11/mark-gibsons-json-jquery-updated/(function ($) { m = {‘\b‘: ‘\\b‘,
‘\t‘: ‘\\t‘,
‘\n‘: ‘\\n‘,
‘\f‘: ‘\\f‘,
‘\r‘: ‘\\r‘,
‘"‘: ‘\\"‘,
‘\\‘: ‘\\\\‘
},
$.toJSON = function (value, whitelist) {var a, // The array holding the partial texts.
i, // The loop counter.
k, // The member key.
l, // Length.
r = /["\\\x00-\x1f\x7f-\x9f]/g,
v; // The member value.
switch (typeof value) {case ‘string‘:
return r.test(value) ?
‘"‘ + value.replace(r, function (a) {var c = m[a];
if (c) {return c;
}
c = a.charCodeAt();
return ‘\\u00‘ + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + ‘"‘ :‘"‘ + value + ‘"‘;
case ‘number‘:return isFinite(value) ? String(value) : ‘null‘;
case ‘boolean‘:case ‘null‘:
return String(value);
case ‘object‘:
if (!value) {return ‘null‘;
}
if (typeof value.toJSON === ‘function‘) {return $.toJSON(value.toJSON());
}
a = [];
if (typeof value.length === ‘number‘ && !(value.propertyIsEnumerable(‘length‘))) {l = value.length;
for (i = 0; i < l; i += 1) {a.push($.toJSON(value[i], whitelist) || ‘null‘);
}
return ‘[‘ + a.join(‘,‘) + ‘]‘;
}
if (whitelist) {l = whitelist.length;
for (i = 0; i < l; i += 1) {k = whitelist[i];
if (typeof k === ‘string‘) {
v = $.toJSON(value[k], whitelist);
if (v) { a.push($.toJSON(k) + ‘:‘ + v);}
}
}
} else { for (k in value) {if (typeof k === ‘string‘) {
v = $.toJSON(value[k], whitelist);
if (v) { a.push($.toJSON(k) + ‘:‘ + v);}
}
}
}
return ‘{‘ + a.join(‘,‘) + ‘}‘;}
};
})(jQuery);
评论(0)