[英]ASP.NET MVC : 2d array is null after being passed from javascript to MVC controller action
I have a 2d array of strings (12x5) that I want to pass from a javascript function to an asp.net mvc controller action. 我有一个二维字符串数组(12x5),我想将其从javascript函数传递给asp.net mvc控制器动作。 Using developer tools in IE I know that the array is populated with what I want it to be, so the issue is in or around the post function.
使用IE中的开发人员工具,我知道该数组填充了我想要的内容,因此问题出在post函数之内或周围。
var dateArray = new Array();
//Populate Data
$.post("/Event/SetDateCalculationParameters", { dates: dateArray }, function () {
//Stuff
});
}
And here is the MVC controller action 这是MVC控制器动作
public ActionResult SetDateCalculationParameters(string[][] dates)
{
//Do stuff
return Json(true);
}
In the controller action, there are 12 items in the dates array, but they are all null. 在控制器操作中,dates数组中有12个项目,但它们均为空。 Ive been at this for a couple hours and am stumped.
我已经在这个地方呆了几个小时而感到困惑。 Is there an easier way to do this?
有没有更简单的方法可以做到这一点? Or am I missing something?
还是我错过了什么?
You could send them as a JSON request: 您可以将它们作为JSON请求发送:
var dateArray = new Array();
dateArray[0] = [ 'foo', 'bar' ];
dateArray[1] = [ 'baz', 'bazinga' ];
// ... and so on
$.ajax({
url: '@Url.Action("SetDateCalculationParameters", "Event")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ dates: dateArray }),
success: function (result) {
}
});
The action signature must look like this: 动作签名必须如下所示:
[HttpPost]
public ActionResult SetDateCalculationParameters(string[][] dates)
To solve the same problem I have created JsonModelBinder and JsonModelAttribute that should be applied to the parameter: 为了解决相同的问题,我创建了JsonModelBinder和JsonModelAttribute,应将其应用于参数:
public class JsonModelBinder : IModelBinder
{
private readonly static JavaScriptSerializer _serializer = new JavaScriptSerializer();
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
if (string.IsNullOrEmpty(stringified))
return null;
return _serializer.Deserialize(stringified, bindingContext.ModelType);
}
}
public class FromJsonAttribute : CustomModelBinderAttribute
{
public override IModelBinder GetBinder()
{
return new JsonModelBinder();
}
}
Your controller will look as follow: 您的控制器将如下所示:
public ActionResult SetDateCalculationParameters([FromJson]string[][] dates)
Also you should stringify your array: 另外,您应该对数组进行字符串化:
$.post("/Event/SetDateCalculationParameters", { dates: JSON.stringify(dateArray)}, function () { //Stuff }); }
It works for me. 这个对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.