我有一个模型类如下:
namespace MvcApplication1.Models
{
public enum Sex { Male, Female };
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
[Required(ErrorMessage="Please select either Female or Male.")]
public Sex? Sex { get; set; }
}
}
Edit
操作确实:
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Edit()
{
var Person = new Person { Id = 1, Name = "Someone", Sex = Sex.Male };
return View(Person);
}
}
}
如何标记Edit
视图,以便有一个包含3个选项的下拉控件:“ - Select - ”,“Female”和“Male”。对于传递给视图的Person
,必须选择“男性”。
如何构成Create
视图并保留下拉控件默认选择“--Select - ”。
以下是Create
操作:
public ActionResult Create()
{
var Person = new Person();
return View(Person);
}
答案 0 :(得分:3)
有一个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");
行中断。了解如何在视图中更改表单值,然后在发布到操作中执行您需要执行的操作?除了使用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--”作为默认选项。