将int数组传递给MVC控制器

Passing an int array to MVC Controller

本文关键字:MVC 控制器 int 数组      更新时间:2023-09-26

我正试图将一个int数组从JavaScript传递给一个MVC控制器,该控制器接受两个参数-一个int阵列和一个int。这是为了执行对控制器操作返回的视图的页面重定向。

var dataArray = getAllIds(); //passes back a JavaScript array 
window.location.replace("/" + controllerName + "/EditAll?ids=" + dataArray + "&currentID=" + dataArray[0])

dataArray包含1.7,正如我的示例用法所预期的那样。

控制器代码

public virtual ActionResult EditAll(int[] ids, int currentID)
{
  currentModel = GetID(currentID);
  currentVM = Activator.CreateInstance<ViewModel>();
  currentVM.DB = DB;
  currentVM.Model = currentModel;
  currentVM.ViewMode = ViewMode.EditAll;
  currentVM.ModelIDs = ids;
  if (currentModel == null)
  {
      return HttpNotFound();
  }
  return View("Edit", MasterName, currentVM);
}

问题是,当检查传递给控制器的int[]id时,它的值为null。currentID按预期设置为1。

我已经尝试过将jQuery.ajaxSettings.cultural=true设置为true,但没有效果我还尝试过在JavaScript中使用@url.Action创建服务器端url。在传递数组之前,我也尝试了JSON.Stringify,例如

window.location.replace("/" + controllerName + "/EditAll?ids=" + JSON.stringify(dataArray) + "&currentID=" + dataArray[0])

id数组在控制器端再次为null。

有没有人有任何指针可以让int数组正确地传递给控制器?我可以在控制器操作中将参数声明为String,并手动序列化和反序列化参数,但我需要了解如何让框架自动进行简单的类型转换。

谢谢!

要在MVC中传递一个简单值的数组,只需为多个值赋予相同的名称。例如,URI最终看起来像这样的

/{controllerName}/EditAll?ids=1&ids=2&ids=3&ids=4&ids=5&currentId=1

MVC中的默认模型绑定会将其正确绑定到int数组Action参数。

现在,如果它是一个复杂值的数组,那么有两种方法可以用于模型绑定。假设你有一个类似的类型

public class ComplexModel
{
    public string Key { get; set; }
    public string Value { get; set; }
}

以及的控制器动作签名

public virtual ActionResult EditAll(IEnumerable<ComplexModel> models)
{
}

为了正确绑定模型,值需要在请求中包括索引器,例如

/{controllerName}/EditAll?models[0].Key=key1&models[0].Value=value1&models[1].Key=key2&models[1].Value=value2

我们在这里使用的是int索引器,但您可以想象,在一个应用程序中,在UI中呈现给用户的项可以在集合中的任何索引/槽处添加和删除,这可能非常不灵活。为此,MVC还允许您为集合中的每个项指定自己的索引器,并将该值与要使用的默认模型绑定的请求一起传递,例如

/{controllerName}/EditAll?models.Index=myOwnIndex&models[myOwnIndex].Key=key1&models[myOwnIndex].Value=value1&models.Index=anotherIndex&models[anotherIndex].Key=key2&models[anotherIndex].Value=value2

在这里,我们为模型绑定指定了自己的索引器myOwnIndexanotherIndex,用于绑定复杂类型的集合。据我所知,您可以为索引器使用任何字符串。

或者,您可以实现自己的模型绑定器,以规定传入请求应如何绑定到模型。这需要比使用默认框架约定更多的工作,但确实增加了另一层灵活性。