如何发布与JSON,jQuery的ASP.NET MVC控制器的复杂对象的数组?

我目前的代码如下所示。 如何将我的数组传递给控制器​​,以及我的控制器动作必须接受哪种参数?

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

我的控制器操作方法看起来像

 public JsonResult SaveOrUpdate(IList<PageDesignWidget> widgets) 

我find了一个解决scheme。 我使用了Steve Gentile, jQuery和ASP.NET MVC的解决scheme– 将JSON发送给Action – Revisited

我的ASP.NET MVC视图代码如下所示:

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

我的控制器操作是用自定义属性装饰的

 [JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignWidget>))] public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets 

自定义属性的代码可以在这里find(链接现在被破坏)。

因为链接被破坏,所以这是JsonFilterAttribute的代码

 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

行动filter,jquery stringify,bleh …

彼得,这个function是原生的MVC。 这是使MVC如此伟大的事情之一。

 $.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) { ... }); 

而在行动中,

 [HttpPost] public ActionResult Batch(string[] ids) { } 

奇迹般有效:

在这里输入图像描述

如果您使用jQuery 1.4+,那么您需要考虑设置传统模式:

 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

.NET4.5MVC 5不需要小部件。

使用Javascript:

JS中的对象: 在这里输入图像描述

机制,发布。

  $('.button-green-large').click(function() { $.ajax({ url: 'Quote', type: "POST", dataType: "json", data: JSON.stringify(document.selectedProduct), contentType: 'application/json; charset=utf-8', }); }); 

C#

对象:

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

控制器:

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Quote(WillsQuoteViewModel data) { .... } 

收到的对象:

在这里输入图像描述

希望这可以为你节省一些时间。

对于使用ASP.NET MVC创buildREST API的后半部分, 其中讲到JSON和纯XML ,引用:

现在我们需要接受通过HTTP POST传递的JSON和XML负载。 有时你的客户可能希望一次上传一批对象进行批处理。 所以,他们可以使用JSON或XML格式上传对象。 在ASP.NET MVC中没有本地支持来自动parsing发布的JSON或XML,并自动映射到Action参数。 所以,我写了一个filter,做到了。“

然后,他实现一个动作filter,将JSON映射到显示代码的C#对象。

首先下载这个JavaScript代码JSON2.js ,这将帮助我们将对象序列化成一个string。

在我的例子中,我通过Ajax发布了一个jqGrid的行:

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

现在在控制器上:

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

创build一个JsonFilter类(感谢JSC参考)。

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

创build另一个类,以便filter可以将JSONstringparsing为实际的可操作对象:此类comissionsJS是我的jqGrid的所有行。

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

我希望这个例子有助于说明如何发布一个复杂的对象。

  [HttpPost] public bool parseAllDocs([FromBody] IList<docObject> data) { // do stuff }