我遇到了一个令人沮丧的问题,当回发到 Controller 时,我似乎无法让模型绑定(bind)与 CheckBoxFor 一起使用。我的模型只是返回 null。任何帮助将不胜感激!
查看
@model IEnumerable<FFR.Context.Matchup>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View1</title>
</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>
Controller
[HttpPost]
public ActionResult Submit(IEnumerable<Matchup> model)
{
//processing
}
型号
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; }
}
最佳答案
您需要使用 for
循环,以便您的控件使用索引器正确命名。将模型更改为 @model IList<FFR.Context.Matchup>
然后在 View 中
for(int i = 0; i < Model.Count; i++)
{
@Html.CheckBoxFor(m => m[i].isChecked)
....
}
如果您无法使用IList
那么你可以使用自定义EditorTemplate
对于您的模型( refer this example )
旁注:为什么要使用Layout = null;
并渲染head
在 View 中(而不是指定布局)?
关于C# MVC Html.CheckBoxFor 不绑定(bind)到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28080587/