将数组从视图发送到控制器并获取null异常错误

时间:2013-08-21 20:04:41

标签: jquery ajax asp.net-mvc-4

我正在使用JQuery从HTML表创建数据数组,我需要将这些数组传递给ASP.NET MVC 4中的控制器方法。

var data = {
InstallationControls: array_installationControl,
HardwareGUIDs: array_HardwareGUID,
InstallAppIDs: array_InstallAppID,
MACAddresses: array_MACAddress
};

$.ajax({
url: "@Url.Content("~/Home/ActivationManagement")",
type: "POST",
data: {data: data},
success: function(){
   console.log('success!!');
}
})

public class MACAddress
    {
        public String Key { get; set; }
        public String Value { get; set; }
    }
public class MyViewModel
    {
        public List<MACAddress> MACAddresses { get; set; }
    }

public ActionResult ActivationManagement(MyViewModel model)
{
List<MACAddress> listOfMacAddresses= model.MACAddresses;
}

但是我得到一个NullReferenceException,说我的listOfMacAddresses对象为null。我做错了吗?感谢

1 个答案:

答案 0 :(得分:0)

请将HttpPost添加到您的代码中,如下所示:

[HttpPost]
public ActionResult ActivationManagement(MyViewModel model)
{
   List<MACAddress> listOfMacAddresses= model.MACAddresses;
   return View();
}

并注意在ajax方法中传递的模型。动作方法中的参数与ajax post中的视图模型不对应。