Asp.net mvc 3 - JSON post & AOP
1. Ajax call Asp.net MVC action
function save() { var data = { 'Name': $('#name').val(), 'Age': $('#age').val() }; $.ajax({ url: '/user/Detail', //'@Url.Action("Detail", "user")', data: JSON.stringify(data), type: 'POST', contentType: 'application/json', //'application/json; charset=utf-8', dataType: 'json', success: function (result) { // } }); }
public class UserController : Controller{ public ActionResult Detail(string Name, string Age){ User user = new Usr(); user.Name = Name; user.Age = Age; return View("Detail", user); } }
summarization:
1. How to post JSON and get
1.1 client passed data type is "json",
must add ---> contentType: 'application/json; charset=UTF-8', dataType: 'json',
change the literal object to string using method: data: JSON.stringify(data),
1.2 MVC recieve the data with
public ActionResult Detail(string Name, string Age){ // each parameter match the passed json data's each parameter.
or
public ActionResult Detail(User user){ // auto ORM.
1.3 passd the data cannot be retrieved by Request.Form.
2. How to post data(application/x-www-form-urlencoded) and get
2.1 if the client doesn't specify contentType, by default, the content type is 'application/x-www-form-urlencoded; charset=UTF-8', the
server can get the data with following, but still cannot b retrieved by Request.Form.
StreamReader sr = new StreamReader(Request.InputStream, Request.ContentEncoding);
string m = sr.ReadToEnd();
2.2 How to post data JSON and get with filter. IActionFilter is the AOP implementation in Asp.net Mvc. In filter, get the parameter as
follow.
filterContext.Controller.ValueProvider.GetValue("Name").AttemptedValue;
[MyAttribute(Message="TestJson")] public ActionResult Detail(){....} public class MyAttribute : FilterAttribute, IActionFilter { public string Message { get; set; } public void OnActionExecuting(ActionExecutingContext filterContext) // before executing the method { filterContext.Controller.ValueProvider.GetValue("Name").AttemptedValue; filterContext.HttpContext.Response.Write( string.Format("[Before Action: {0}]", Message)); } public void OnActionExecuted(ActionExecutedContext filterContext) // after executed the method { filterContext.HttpContext.Response.Write( string.Format("[After Action: {0}]", Message)); } }
3. 1 Request.Form works in asp.net mvc, if the dataType is by default and data is '{a:'1', b:'2'}'.
$.ajax({ url: '/user/Detail', data: {name: 'Tom'}, // have a test by enclosing name with single quote if test failed. type: 'POST', success: function (result) { alert(result); }, error: function (xhRequest, text, thrownError) { alert(xhRequest); } });