简体   繁体   English

在c#asp.net ajax POST请求中读取请求有效负载

[英]Read request payload in c# asp.net ajax POST request

I am sending a POST ajax request to Home controller in asp.net mvc project. 我在asp.net mvc项目中向Home控制器发送POST ajax请求。 Here is sample javascript. 这是示例javascript。 ( the convertUtcToLocal is basically a function that will return the time to local date ). (convertUtcToLocal基本上是一个将时间返回到本地日期的函数)。

var data = [{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},
{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""}];

$.ajax({url : 'http://localhost:64387/Home/TableEdit', 
        type : 'POST', 
        contentType:'application/json',
        dataType :'json', 
        data : JSON.stringify(data)});

In Home controller I get , 在家庭控制器我得到,

[HttpPost]
        public object TableEdit(object data)
        {
            // object is shown in the Watch as object

        }

In Google Chrome, I can see request payload 在Google Chrome中,我可以看到请求有效负载 在此输入图像描述

How do I access the data in my Home controller action ? 如何访问家庭控制器操作中的数据?

How do I access the data in my Home controller action ? 如何访问家庭控制器操作中的数据?

By writing a view model of course: 通过编写视图模型当然:

public class MyViewModel
{
    public DateTime Time { get; set; }
    public decimal OldValue { get; set; }
    public decimal? NewValue { get; set; }
    public string Action { get; set; }
}

and then having your controller action take a collection of this view model as a parameter: 然后让控制器操作将此视图模型的集合作为参数:

[HttpPost]
public ActionResult TableEdit(IList<MyViewModel> data)
{
    ... do something with the view model here
}

By the way, beware of the format of DateTime fields. 顺便提一下,要注意DateTime字段的格式。 Make sure that your application's current culture settings format matches the one in your JSON. 确保应用程序的当前文化设置格式与JSON中的格式匹配。 You also might need to adjust the data types used in your view model depending on your specific requirements. 您还可能需要根据具体要求调整视图模型中使用的数据类型。

Basically, you're are passing a JSON string, so the action method in the controller will accept a string and you can use Newtonsoft.Json to convert it into a model . 基本上,您正在传递JSON字符串,因此控制器中的action method将接受一个字符串,您可以使用Newtonsoft.Json将其转换为model

Pass JSON data: 传递JSON数据:

$.ajax({
                url: '/Home/TableEdit',
                type: 'POST',
                data: { "modelData": result }
            });

and controller action method as 和控制器动作方法为

   [HttpPost]
    public ActionResult TableEdit(string modelData)
    {
        List<ViewModel> listOfModel = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model>>(modelData);
        return View();
    }

So this is how I solved my problem. 所以这就是我解决问题的方法。 Using Newtonsoft.Json.Linq 使用Newtonsoft.Json.Linq

Here is the custom model binder and the controller. 这是自定义模型绑定器和控制器。

   public class TableEditCustomBinder : IModelBinder
        {
            public object BindModel(ControllerContext controllerContext,
                            ModelBindingContext bindingContext)
            {
                var incomingData = bindingContext.ValueProvider.GetValue("data").AttemptedValue;
                JObject root = JObject.Parse("{\"root\": " + incomingData + "}");
                JArray items = (JArray)root["root"];
                JObject item;
                JToken jtoken;
                List<TableData> data = new List<TableData>();
                string action="" , newValue="", oldValue="", dataType;
                double time=0;
                for (int i = 0; i < items.Count; i++)
                {
                    item = (JObject)items[i];
                    jtoken = item.First;
                    while (jtoken != null)//loop through columns
                    {
                        dataType = ((JProperty)jtoken).Name.ToString().ToLower();

                        switch (dataType)
                        {
                            case "time":
                                time = Convert.ToDouble(((JProperty)jtoken).Value);
                                break;
                            case "newvalue":
                                newValue = ((JProperty)jtoken).Value.ToString();
                                break;
                            case "oldvalue":
                                oldValue = ((JProperty)jtoken).Value.ToString();
                                break;
                            case "action":
                                action = ((JProperty)jtoken).Value.ToString();
                                break;
                            default:
                                break;
                        }
                         jtoken = jtoken.Next;
                    }
                    if (time != 0) {
                        data.Add(new TableData(time, oldValue));
                        data[data.Count-1].NewValue = newValue;
                        data[data.Count-1].Action = action;
                    }

                }

                return data;

            }
        }
        [HttpPost]
        public object TableEdit(string server, string tag, [ModelBinder(typeof(TableEditCustomBinder))] List<TableData> data)      
        {         
            //Use data the way you want
        }

The ajax request. ajax请求。 I am passing time as UTC string. 我正在以UTC字符串的形式传递时间。 But can be handled in the code otherwise. 但是否则可以在代码中处理。

$.ajax({url: 'http://localhost:64387/Home/TableEdit', type : 'POST', 
        contentType:"application/x-www-form-urlencoded",
        dataType :'json', 
        data : { server: "server", tag : "xyz", data : JSON.stringify(data)}});

Also don't forget to put this in Application_Start()' method in Global.asax.cs' 另外不要忘记将它放在Global.asax.cs中的Application_Start()' method in

ModelBinders.Binders.Add(typeof(List<TableData>), new HomeController.TableEditCustomBinder()); I hope it helps others. 我希望它能帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM