C# MVC Html.CheckBoxFor not binding to model
我遇到了一个令人沮丧的问题,当我发回控制器时,我似乎无法让模型绑定与 CheckBoxFor 一起使用。我的模型只是返回 null。任何帮助将不胜感激!
查看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | @model IEnumerable<FFR.Context.Matchup> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> View1 </head> <body> <p> @Html.ActionLink("Create New","Create") </p> @using (Html.BeginForm(Html.BeginForm("Submit","Matchups", FormMethod.Post))) { @foreach (var item in Model) { <tr> <td>@Html.CheckBoxFor(modelItem => item.isChecked)</td> <td> @Html.DisplayFor(modelItem => item.MatchupDate) </td> <td> @Html.DisplayFor(modelItem => item.Spread) </td> <td> @Html.DisplayFor(modelItem => item.HomeScore) </td> <td> @Html.DisplayFor(modelItem => item.AwayScore) </td> } <tr><td><input type="submit" value="Submit" /></td></tr> </table> } </body> </html> |
控制器
1 2 3 4 5 6 7 | [HttpPost] public ActionResult Submit(IEnumerable<Matchup> model) { //processing } |
型号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public partial class Matchup { public Matchup() { this.Bets = new HashSet<Bet>(); } public int MatchupId { get; set; } public int HomeTeamId { get; set; } public int AwayTeamId { get; set; } public int LocationId { get; set; } public System.DateTime MatchupDate { get; set; } public int WeekId { get; set; } public int SeasonId { get; set; } public Nullable<decimal> Spread { get; set; } public Nullable<decimal> HomeScore { get; set; } public Nullable<decimal> AwayScore { get; set; } public string TimeLeft { get; set; } public Nullable<System.DateTime> LastUpdate { get; set; } public Boolean isChecked { get; set; } } |
您需要使用
1 2 3 4 5 | for(int i = 0; i < Model.Count; i++) { @Html.CheckBoxFor(m => m[i].isChecked) .... } |
如果你不能使用
旁注:为什么要使用
希望此链接能让您深入了解模型绑定如何与列表一起使用。
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
请注意,您在视图中执行的操作过多。尝试为更简单的视图使用编辑器模板。
我还注意到 2 次调用 Begin 表单。你真的打算这样使用吗?