将int数组传递给MVC Controller

Sco*_*and 5 javascript arrays model-view-controller asp.net-mvc jquery

我正在尝试将一个int数组从JavaScript传递给一个接受2个参数的MVC控制器 - 一个int数组和一个int.这是执行页面重定向到Controller Action返回的视图.

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

我已经尝试设置jQuery.ajaxSettings.traditional = true这没有效果我也尝试在JavaScript中使用@ Url.Action创建服务器端URL.在传递数组之前我也尝试过JSON.Stringify

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

同样,id数组在控制器端最终为null.

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

谢谢!

Rus*_*Cam 10

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

/{controllerName}/EditAll?ids=1&ids=2&ids=3&ids=4&ids=5&currentId=1
Run Code Online (Sandbox Code Playgroud)

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

现在,如果它是一个复杂值的数组,则可以采用两种方法进行模型绑定.我们假设您有类似的类型

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

    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和控制器动作签名

public virtual ActionResult EditAll(IEnumerable<ComplexModel> models)
{
}
Run Code Online (Sandbox Code Playgroud)

对于正确的模型绑定,值需要在请求中包含索引器,例如

/{controllerName}/EditAll?models[0].Key=key1&models[0].Value=value1&models[1].Key=key2&models[1].Value=value2
Run Code Online (Sandbox Code Playgroud)

我们使用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
Run Code Online (Sandbox Code Playgroud)

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

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