我有一个枚举:
[Flags]
public enum DayOfWeekEnum
{
None = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
All = 31
}
我想以一个复选框列表的形式在asp.net mvc应用程序中显示它。
我找到了这段代码:
@foreach (DayOfWeekEnum item in Enum.GetValues(typeof(DayOfWeekEnum)))
{
if (item > 0 && item <= DayOfWeekEnum.Friday)
{
@Html.Label("DayOfWeekEnum", item.ToString())
@Html.CheckBox("DayOfWeekEnum", (Model.Availability.HasFlag(item)),
new {value = item})
}
}
但是,它不会将值发送回控制器。
模型看起来像这样:
public class Teacher
{
public int Id { get; set; }
public User User { get; set; }
public Level Level { get; set; }
public DayOfWeekEnum Availability { get; set; }
}
控制器看起来像这样:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,User,Level,Availability")] Teacher
teacher)
{
if (ModelState.IsValid)
{
serviceClient.AddTeacher(teacher);
return RedirectToAction("Index");
}
return View(teacher);
}
答案 0 :(得分:-1)
更改
@Html.CheckBox("DayOfWeekEnum", (Model.Availability.HasFlag(item)), new {value = item})
为:
@Html.CheckBox("DayOfWeekEnum", (Model.Availability.HasFlag(item)), new {value = (int)item})
它应该从以下位置更新您的源代码:
<label for="DayOfWeekEnum">Monday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="Monday" />
<label for="DayOfWeekEnum">Tuesday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="Tuesday" />
<label for="DayOfWeekEnum">Wednesday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="Wednesday" />
<label for="DayOfWeekEnum">Thursday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="Thursday" />
<label for="DayOfWeekEnum">Friday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="Friday" />
为:
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="1" />
<label for="DayOfWeekEnum">Tuesday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="2" />
<label for="DayOfWeekEnum">Wednesday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="4" />
<label for="DayOfWeekEnum">Thursday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="8" />
<label for="DayOfWeekEnum">Friday</label>
<input id="DayOfWeekEnum" name="DayOfWeekEnum" type="checkbox" value="16" />
这应该发送正确的值。