ASP.NET MVC:2d数组在从javascript传递到MVC控制器操作后为null

ASP.NET MVC : 2d array is null after being passed from javascript to MVC controller action

本文关键字:MVC 控制器 操作 null javascript NET 2d 数组 ASP      更新时间:2024-02-18

我有一个2d字符串数组(12x5),我想将其从javascript函数传递给asp.net mvc控制器操作。使用IE中的开发人员工具,我知道数组中填充了我想要的内容,所以问题出在post函数中或其周围。

var dateArray = new Array();
//Populate Data
$.post("/Event/SetDateCalculationParameters", { dates: dateArray }, function () {
    //Stuff
});
}

这是MVC控制器动作

public ActionResult SetDateCalculationParameters(string[][] dates)
    {
        //Do stuff
        return Json(true);
    }

在控制器操作中,日期数组中有12个项目,但它们都为空。我已经做了几个小时了,被难住了。有更简单的方法吗?还是我错过了什么?

您可以将它们作为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) {
    }
});

动作签名必须如下所示:

[HttpPost]
public ActionResult SetDateCalculationParameters(string[][] dates)

为了解决同样的问题,我创建了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();
    }
}

您的控制器将如下所示:

public ActionResult SetDateCalculationParameters([FromJson]string[][] dates)

此外,你应该字符串化你的数组:

$.post("/Event/SetDateCalculationParameters", { dates: JSON.stringify(dateArray)}, function () {             //Stuff         });         }

它对我有效。