0
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方法中創建的模型? 我做錯了什麼?
Nevaran初始化構造函數中的Dictionary意味着在Model Constructor中爲字典分配一個內存。 – Shivkumar