Asp.net mvc 3 - JSON post & AOP

本文介绍了如何使用Ajax与ASP.NET MVC进行数据交互,包括发送JSON格式的数据及通过过滤器处理请求的方法。详细讲述了客户端如何将JSON数据发送到服务器端,并在服务器端接收这些数据。此外还介绍了使用IActionFilter在请求前后的处理过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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);  
                }
            });

转载于:https://www.cnblogs.com/webglcn/archive/2012/08/24/2654446.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值