我当前的代码如下所示。如何将我的数组传递给 Controller ,我的 Controller Action 必须接受什么样的参数?
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");
};
我的 Controller Action 方法看起来像
public JsonResult SaveOrUpdate(IList<PageDesignWidget> widgets)
最佳答案
我找到了解决方案。我使用 Steve Gentile 的解决方案, jQuery and ASP.NET MVC – sending JSON to an Action – Revisited .
我的 ASP.NET MVC View 代码如下所示:
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);
}
});
};
我的 Controller Action 被自定义属性修饰
[JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignWidget>))]
public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets
可以找到自定义属性的代码 here (链接现在断开了)。
由于链接已损坏,这是 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
关于c# - 如何将带有 JSON、jQuery 的复杂对象数组发布到 ASP.NET MVC Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/320291/