将 Javascript 数组传递给 ASP.NET MVC 控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10042608/
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
Passing Javascript array to ASP.NET MVC Controller
提问by Lance
I have the following javascript class which I am trying to pass to an ASP.NET MVC Controller
我有以下 javascript 类,我试图将其传递给 ASP.NET MVC 控制器
var postParams = {
attributes : [
{
name : '',
description: '',
attributeType : '',
value : ''
}
]
};
postParams.attributes[0] = new Object();
postParams.attributes[0].name = "test";
postParams.attributes[0].description = "test";
postParams.attributes[0].attributeType = "test";
postParams.attributes[0].value = "test";
Here's how I call the Controller method:
下面是我调用 Controller 方法的方式:
var actionURL = "@Url.Action("Save", "Catalog")";
$.ajax({
type: "POST",
url: actionURL,
data: postParams ......
On the Controller side I've declared a ViewModel as follows:
在控制器端,我声明了一个 ViewModel,如下所示:
public class AttributeViewModel
{
public string name { get; set; }
public string description { get; set; }
public string attributeType { get; set; }
public string value { get; set; }
}
My Controller Save method is declared as follows:
我的控制器保存方法声明如下:
public JsonResult Save(AttributeViewModel[] attributes)
When I execute the value of attributes is always null.
当我执行属性的值总是为空。
Any ideas? Not sure how to even start debugging this.
有任何想法吗?不知道如何开始调试这个。
回答by Sanja Melnichuk
You can try json.netlibrary to solve your issue
您可以尝试使用json.net库来解决您的问题
[JsonFilter(Param = "attributes", JsonDataType = typeof(AttributeViewModel[]))]
public JsonResult Save(AttributeViewModel[] attributes)
At client:
在客户端:
$.ajax({
type: 'POST',
url: url,
async: true,
data: JSON.stringify(attributes), //!!! Here must be the same name as in controller method
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});