有一个good answer already on how to convert an Enum into a SelectList,但我会内联重用该代码来简单地回答。
public ActionResult Edit()
{
var Person = new Person { Id = 1, Name = "Someone", Sex = Sex.Male };
List<object> values = new List<object>();
values.Add(new { ID = "choose", Name = "--Select--" });
values.AddRange(from Sex sex in Enum.GetValues(typeof(Sex))
select new { ID = sex, Name = sex.ToString() });
ViewData["sexes"] = new SelectList(values, "Id", "Name", Person.Sex);
return View(Person);
}
现在是 Edit.cshtml 视图:
@model Test.Models.Person
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Sex)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Sex, (SelectList)ViewData["sexes"])
@Html.ValidationMessageFor(model => model.Sex)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
现在将表单发布到的控制操作:
[HttpPost]
public ActionResult Edit(Person person)
{
var newName = person.Name;
var newSex = person.Sex;
return RedirectToAction("index", "home");
}
现在在调试模式下运行项目,并在 post-to Edit 操作中的 return RedirectToAction("index", "home"); 行中断。看看如何在视图中更改表单值,然后在 post-to 操作中执行您需要执行的操作?除了使用 ViewData 传递列表之外,还有其他选项,但它们使示例复杂化并且数量众多。
Create 操作如下所示:
public ActionResult Create()
{
Person person = new Person();
List<object> values = new List<object>();
values.Add(new { ID = "choose", Name = "--Select--" });
values.AddRange(from Sex sex in Enum.GetValues(typeof(Sex))
select new { ID = sex, Name = sex.ToString() });
ViewData["sexes"] = new SelectList(values, "Id", "Name");
return View(person);
}
默认选择列表项将是第一个,因此它将显示“--Select--”作为默认选项。