How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?
我当前的代码如下所示。 如何将我的数组传递给控制器以及控制器操作必须接受哪种参数?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function getplaceholders() { var placeholders = $('.ui-sortable'); var result = new Array(); placeholders.each(function() { var ph = $(this).attr('id'); var sections = $(this).find('.sort'); var section; sections.each(function(i, item) { var sid = $(item).attr('id'); result.push({ 'SectionId': sid, 'Placeholder': ph, 'Position': i }); }); }); alert(result.toString()); $.post( '/portal/Designer.mvc/SaveOrUpdate', result, function(data) { alert(data.Result); },"json"); }; |
我的控制器动作方法看起来像
1 | public JsonResult SaveOrUpdate(IList<PageDesignWidget> widgets) |
我找到了解决方案。我使用Steve Gentile,jQuery和ASP.NET MVC的解决方案 - 将JSON发送到Action - Revisited。
我的ASP.NET MVC视图代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function getplaceholders() { var placeholders = $('.ui-sortable'); var results = new Array(); placeholders.each(function() { var ph = $(this).attr('id'); var sections = $(this).find('.sort'); var section; sections.each(function(i, item) { var sid = $(item).attr('id'); var o = { 'SectionId': sid, 'Placeholder': ph, 'Position': i }; results.push(o); }); }); var postData = { widgets: results }; var widgets = results; $.ajax({ url: '/portal/Designer.mvc/SaveOrUpdate', type: 'POST', dataType: 'json', data: $.toJSON(widgets), contentType: 'application/json; charset=utf-8', success: function(result) { alert(result.Result); } }); }; |
我的控制器动作用自定义属性修饰
1 2 | [JsonFilter(Param ="widgets", JsonDataType = typeof(List<PageDesignWidget>))] public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets |
可以在此处找到自定义属性的代码(链接现在已断开)。
因为链接被破坏,所以这是JsonFilterAttribute的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class JsonFilter : ActionFilterAttribute { public string Param { get; set; } public Type JsonDataType { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Request.ContentType.Contains("application/json")) { string inputContent; using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream)) { inputContent = sr.ReadToEnd(); } var result = JsonConvert.DeserializeObject(inputContent, JsonDataType); filterContext.ActionParameters[Param] = result; } } } |
JsonConvert.DeserializeObject来自Json.NET
链接:使用Json.NET序列化和反序列化JSON
动作过滤器,jquery stringify,bleh ......
Peter,这个功能是MVC原生的。这是让MVC如此出色的事情之一。
1 2 3 | $.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) { ... }); |
在行动中,
1 2 3 4 | [HttpPost] public ActionResult Batch(string[] ids) { } |
奇迹般有效:
如果你正在使用jQuery 1.4+,那么你想看看设置传统模式:
1 | jQuery.ajaxSettings.traditional = true; |
如下所述:http://www.dovetailsoftware.com/blogs/kmiller/archive/2010/02/24/jquery-1-4-breaks-asp-net-mvc-actions-with-array-parameters
这甚至适用于复杂的物体。如果您有兴趣,可以查看有关模型绑定的MVC文档:http://msdn.microsoft.com/en-us/library/dd410405.aspx
在
使用Javascript:
JS中的对象:
发布的机制。
1 2 3 4 5 6 7 8 9 | $('.button-green-large').click(function() { $.ajax({ url: 'Quote', type:"POST", dataType:"json", data: JSON.stringify(document.selectedProduct), contentType: 'application/json; charset=utf-8', }); }); |
C#
对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class WillsQuoteViewModel { public string Product { get; set; } public List<ClaimedFee> ClaimedFees { get; set; } } public partial class ClaimedFee //Generated by EF6 { public long Id { get; set; } public long JourneyId { get; set; } public string Title { get; set; } public decimal Net { get; set; } public decimal Vat { get; set; } public string Type { get; set; } public virtual Journey Journey { get; set; } } |
控制器:
1 2 3 4 5 | [AcceptVerbs(HttpVerbs.Post)] public ActionResult Quote(WillsQuoteViewModel data) { .... } |
收到的对象:
希望这能为您节省一些时间。
使用同时使用JSON和纯XML的ASP.NET MVC创建REST API的下半部分,引用:
Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."
然后,他实现了一个动作过滤器,它将JSON映射到C#对象,并显示代码。
首先下载这个JavaScript代码JSON2.js,它将帮助我们将对象序列化为字符串。
在我的例子中,我通过Ajax发布了jqGrid的行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var commissions = new Array(); // Do several row data and do some push. In this example is just one push. var rowData = $(GRID_AGENTS).getRowData(ids[i]); commissions.push(rowData); $.ajax({ type:"POST", traditional: true, url: '<%= Url.Content("~/") %>' + AREA + CONTROLLER + 'SubmitCommissions', async: true, data: JSON.stringify(commissions), dataType:"json", contentType: 'application/json; charset=utf-8', success: function (data) { if (data.Result) { jQuery(GRID_AGENTS).trigger('reloadGrid'); } else { jAlert("A problem ocurred during updating","Commissions Report"); } } }); |
现在在控制器上:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | [HttpPost] [JsonFilter(Param ="commissions", JsonDataType = typeof(List<CommissionsJs>))] public ActionResult SubmitCommissions(List<CommissionsJs> commissions) { var result = dosomething(commissions); var jsonData = new { Result = true, Message ="Success" }; if (result < 1) { jsonData = new { Result = false, Message ="Problem" }; } return Json(jsonData); } |
创建一个JsonFilter类(感谢JSC参考)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class JsonFilter : ActionFilterAttribute { public string Param { get; set; } public Type JsonDataType { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Request.ContentType.Contains("application/json")) { string inputContent; using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream)) { inputContent = sr.ReadToEnd(); } var result = JsonConvert.DeserializeObject(inputContent, JsonDataType); filterContext.ActionParameters[Param] = result; } } } |
创建另一个类,以便过滤器可以将JSON字符串解析为实际的可操作对象:此类comissionsJS是我的jqGrid的所有行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class CommissionsJs { public string Amount { get; set; } public string CheckNumber { get; set; } public string Contract { get; set; } public string DatePayed { get; set; } public string DealerName { get; set; } public string ID { get; set; } public string IdAgentPayment { get; set; } public string Notes { get; set; } public string PaymentMethodName { get; set; } public string RowNumber { get; set; } public string AgentId { get; set; } } |
我希望这个例子有助于说明如何发布复杂的对象。
哦,我的上帝。不需要做任何特别的事情。仅在您的帖子部分中执行以下操作:
1 | $.post(yourURL,{ '': results})(function(e){ ...} |
在服务器中使用此:
1 | public ActionResult MethodName(List<yourViewModel> model){...} |
这个链接可以帮助你完成......
1 2 3 4 5 6 | [HttpPost] public bool parseAllDocs([FromBody] IList<docObject> data) { // do stuff } |