ModelBinder未正确绑定到提交列表

时间:2011-12-27 05:32:05

标签: asp.net asp.net-mvc asp.net-mvc-3 razor model-binding

我正在尝试正确设置复选框的HTML,以便它们可以绑定到列表属性,但似乎无法成功完成。在下面的视图代码中,我有五个复选框。它只在我检查至少第一个复选框时绑定。如果我检查除第一个复选框之外的所有四个复选框,则不会绑定任何内容。

这是我的代码:

  public class People
  {
    public List<Person> Crew { get; set; }
    public string TeamName { get; set; }

    public List<string> StatesLiveIn { get; set; }

  }

  public class Person
  {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
  }

查看:

@model TestBinder.Models.People

@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm()) 
{ 

  @Html.TextBoxFor(m => m.TeamName);  


  <h2>Crew #0</h2>
  <h3>FirstName:</h3>                                  
  @Html.TextBoxFor(m => m.Crew[0].FirstName); <br />

  <h3>LastName: </h3>
  @Html.TextBoxFor(m => m.Crew[0].LastName);<br />

  <h3>Age: </h3>
  @Html.TextBoxFor(m => m.Crew[0].Age);<br />


  <h3>States Lived In: </h3>
  int i = 0;
  foreach (string state in new List<string>() { "NY","NJ","FL","IL","TX" })
  {     
    @state <input checked="checked" type="checkbox" value="@state" name="StatesLiveIn[@i]" /><br />  
    i++;
  }                                             

  <input type="submit" value="submit" />
}

控制器:

public ActionResult Index()
{   
  return View();
}

[HttpPost]
public ActionResult Index(People p)
{    
  return View(p);
}

感谢。

1 个答案:

答案 0 :(得分:2)

尝试给您的复选框命名相同:

<h3>States Lived In: </h3>
foreach (var state in new[] { "NY", "NJ", "FL", "IL", "TX" })
{     
    @state 
    <input checked="checked" type="checkbox" value="@state" name="StatesLiveIn" />
    <br />  
}

但更好的选择是使用视图模型,编辑器模板和强类型CheckBoxFor帮助器,因为您已经对checked="checked"属性进行了硬编码,并且如果存在验证错误并且您在同一视图中呈现POST操作,用户将失去其选择。