具有多个选择和复杂对象的ModelBinder

时间:2010-02-22 11:57:49

标签: c# asp.net asp.net-mvc

我正在尝试将多选SELECT中的选择绑定到控制器中的IList输入。

<select name="users" multiple="multiple">
  <option>John</option>
  <option>Mary</option>
</select>

class User
{
    public string Name { get; set; }
}

//Action
void Update(IList<User> users)
{
}

我尝试将select重命名为“users”,“users.Name”或“users.User.Name”但没有成功。

2 个答案:

答案 0 :(得分:0)

您好有两种方法可以做到这一点。第一种是使用FormCollection,它将结果作为CSV列表返回。所以代码就像:

[HttpPost]
public ActionResult Update(FormCollection collection)
{
    collection[0] 
    // providing this is your first item in your collection you 
    // may need to debug this to find out
}

第二个选项是使用一个类似于:

的参数
[HttpPost]
public ActionResult Update(string[] users)
{
}

如果您在选择框中设置值,如:

<select name="users" multiple="multiple">
    <option value="1">John</option>
    <option value="2">Mary</option>
</select>

然后它将是数组中的值而不是名称,在这种情况下,您的操作可能如下所示:

[HttpPost]
public ActionResult Update(int[] users)
{
}

答案 1 :(得分:0)

尝试使用像这样的ViewModel类:

public class TestViewModel
    {
        public List<string> Users { get; set; }
    }

然后在Action中将ViewModel类设置为输入参数,如下所示:

public ActionResult Save(TestViewModel model)
        {
            return View("Index");
        }

它对我有用。

相关问题