给定模型:
public class RegisterModel
{
<!-- some properties -->
[Required]
public Dictionary<DayOfWeek, bool> DaysAtWork { get; set; }
public RegisterModel()
{
DaysAtWork = new Dictionary<DayOfWeek, bool>
{
{DayOfWeek.Monday, true},
{DayOfWeek.Tuesday, true},
{DayOfWeek.Wednesday, true},
{DayOfWeek.Thursday, true},
{DayOfWeek.Friday, true}
};
}
}
控制器:
public ActionResult Register()
{
var model = new RegisterModel();
return View(model);
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
<!-- and at these point in model state property for DaysAtWork
Dictionary is null and the whole model is invalid - and property in model
parameter is also null -->
if (ModelState.IsValid)
{
<!-- some logic here -->
}
return View(model);
}
并查看:
<!-- some code -->
@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
<div>
<fieldset>
<legend>Account Information</legend>
<div>Days at work</div>
<div>
Monday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Monday])
</div>
<div>
Tuesday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Tuesday])
</div>
<div>
Wednesday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Wednesday])
</div>
<div>
Thursday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Thursday])
</div>
<div>
Friday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Friday])
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
}
我在尝试注册用户时遇到问题,因为在模型中 DaysAtWork 属性设置为 null。如何告诉 asp 使用在 Register() HttpGet 方法中创建的模型?我做错了什么?