如何使用 JSON、jQuery 将一组复杂对象发布到 ASP.NET MVC 控制器? [英] How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?
问题描述
我当前的代码如下所示.如何将我的数组传递给控制器以及我的控制器操作必须接受什么样的参数?
My current code looks like the following. How can I pass my array to the controller and what kind of parameters must my controller action accept?
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");
};
我的控制器操作方法看起来像
My controller action method looks like
public JsonResult SaveOrUpdate(IList<PageDesignWidget> widgets)
推荐答案
我找到了解决方案.我使用 Steve Gentile 的解决方案,jQuery 和 ASP.NET MVC – 将 JSON 发送到操作 –重温.
I've found an solution. I use an solution of Steve Gentile, jQuery and ASP.NET MVC – sending JSON to an Action – Revisited.
我的 ASP.NET MVC 视图代码如下所示:
My ASP.NET MVC view code looks like:
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);
}
});
};
并且我的控制器操作装饰有自定义属性
and my controller action is decorated with an custom attribute
[JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignWidget>))]
public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets
可以在此处找到自定义属性的代码(链接现已失效).
Code for the custom attribute can be found here (the link is broken now).
因为链接已断开,这是 JsonFilterAttribute 的代码
Because the link is broken this is the code for the 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
JsonConvert.DeserializeObject is from Json.NET
这篇关于如何使用 JSON、jQuery 将一组复杂对象发布到 ASP.NET MVC 控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!