我的视图中有一个文本框,其中包含以下值:
“1,3,5,8”或
“1; 3; 5; 8”。
是否可以将这些值作为int数组映射到控制器方法?
[HttpPost]
public ActionResult AddUsers(int[] values)
{
...
}
答案 0 :(得分:0)
网址应如下所示。在JQuery中,您可以根据TextBox值准备URL。
<强> http://abc.com/ControllerName/ActionName/?id=1&id=2 强>
行动方法
[HttpPost]
public ActionResult Index(int[] id)
{
}
答案 1 :(得分:0)
您可以创建自定义模型装订器。添加一个类,比如ArrayIntModelBinder
并实现IModelBinder interface:
public class ArrayIntModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (bindingContext == null)
throw new ArgumentNullException("bindingContext");
string values = bindingContext.ValueProvider.GetValue("values").AttemptedValue;
return Array.ConvertAll(values.Split(new[] { ',', ';' }), int.Parse);
}
}
在视图中,您有文本框:
@using (Html.BeginForm())
{
<input type="text" name="values"/>
<input type="submit" value="submit"/>
}
并将新模型活页夹应用于您的操作
[HttpPost]
public ActionResult AddUsers([ModelBinder(typeof(ArrayIntModelBinder))]int[] values)
{
...
}
或者您可以在Application_Start
。
当然,这个版本的模型绑定器非常简单,只是为了给你一个想法。您必须至少提供输入字符串的一些验证。希望这会有所帮助。