C# 如何使用 JSON、jQuery 将一组复杂对象发布到 ASP.NET MVC 控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/320291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?
提问by JSC
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)
采纳答案by JSC
I've found an solution. I use an solution of Steve Gentile, jQuery and ASP.NET MVC – sending JSON to an Action – Revisited.
我找到了解决办法。我使用 Steve Gentile、jQuery 和 ASP.NET MVC的解决方案——将 JSON 发送到操作——重新访问。
My ASP.NET MVC view code looks like:
我的 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);
}
});
};
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).
可以在此处找到自定义属性的代码(链接现在已断开)。
Because the link is broken this is the code for the JsonFilterAttribute
因为链接已损坏,这是 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 is from Json.NET
JsonConvert.DeserializeObject 来自 Json.NET
回答by anonymous
Towards the second half of Create REST API using ASP.NET MVC that speaks both JSON and plain XML, to quote:
在使用 ASP.NET MVC 创建 REST API 的后半部分,它讲 JSON 和纯 XML,引用:
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."
现在我们需要接受通过 HTTP POST 传递的 JSON 和 XML 有效负载。有时,您的客户可能希望一次性上传一组对象以进行批处理。因此,他们可以使用 JSON 或 XML 格式上传对象。ASP.NET MVC 中没有本机支持来自动解析发布的 JSON 或 XML 并自动映射到 Action 参数。所以,我写了一个过滤器来做到这一点。”
He then implements an action filter that maps the JSON to C# objects with code shown.
然后,他实现了一个动作过滤器,将 JSON 映射到 C# 对象,并显示了代码。
回答by Sanchitos
First download this JavaScript code, JSON2.js, that will help us serialize the object into a string.
首先下载此 JavaScript 代码JSON2.js,它将帮助我们将对象序列化为字符串。
In my example I'm posting the rows of a jqGridvia Ajax:
在我的示例中,我通过 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");
}
}
});
Now on the controller:
现在在控制器上:
[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);
}
Create a JsonFilter Class (thanks to JSC reference).
创建一个 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;
}
}
}
Create another class so the filter can parse the JSON string to the actual manipulable object: This class comissionsJS are all the rows of my jqGrid.
创建另一个类,以便过滤器可以将 JSON 字符串解析为实际的可操作对象:这个类 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; }
}
I hope this example helps to illustrate how to post a complex object.
我希望这个例子有助于说明如何发布一个复杂的对象。
回答by Levitikon
Action Filters, jquery stringify, bleh...
动作过滤器、jquery stringify、bleh...
Peter, this functionality is native to MVC. That's one of things that makes MVC so great.
彼得,这个功能是 MVC 原生的。这是使 MVC 如此伟大的原因之一。
$.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) {
...
});
And in the action,
而在行动中,
[HttpPost]
public ActionResult Batch(string[] ids)
{
}
Works like a charm:
奇迹般有效:
If you're using jQuery 1.4+, then you want to look into setting traditional mode:
如果您使用的是 jQuery 1.4+,那么您需要考虑设置传统模式:
jQuery.ajaxSettings.traditional = true;
As described here: http://www.dovetailsoftware.com/blogs/kmiller/archive/2010/02/24/jquery-1-4-breaks-asp-net-mvc-actions-with-array-parameters
如此处所述:http: //www.dovetailsoftware.com/blogs/kmiller/archive/2010/02/24/jquery-1-4-breaks-asp-net-mvc-actions-with-array-parameters
This even works for complex objects. If you're interested, you should look into the MVC documentation about Model Binding: http://msdn.microsoft.com/en-us/library/dd410405.aspx
这甚至适用于复杂的对象。如果您有兴趣,您应该查看有关模型绑定的 MVC 文档:http: //msdn.microsoft.com/en-us/library/dd410405.aspx
回答by Matas Vaitkevicius
In .NET4.5
, MVC 5
no need for widgets.
在 中.NET4.5
,MVC 5
不需要小部件。
Javascript:
Javascript:
object in JS:
JS中的对象:
mechanism that does post.
发布的机制。
$('.button-green-large').click(function() {
$.ajax({
url: 'Quote',
type: "POST",
dataType: "json",
data: JSON.stringify(document.selectedProduct),
contentType: 'application/json; charset=utf-8',
});
});
C#
C#
Objects:
对象:
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; }
}
Controller:
控制器:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}
Object received:
收到的对象:
Hope this saves you some time.
希望这可以为您节省一些时间。
回答by JsonW
[HttpPost]
public bool parseAllDocs([FromBody] IList<docObject> data)
{
// do stuff
}
回答by mahdi moghimi
Oh my God. not need to do anything special. only in your post section do as follows:
我的天啊。不需要做任何特别的事情。仅在您的帖子部分执行以下操作:
$.post(yourURL,{ '': results})(function(e){ ...}
In server use this:
在服务器中使用这个:
public ActionResult MethodName(List<yourViewModel> model){...}
this linkhelp you to done ...
此链接可帮助您完成...