我有一个页面用于在我的Database.One字段中的某个表中插入新行。该字段是同一个表中父项的外键。所以我想要一个drobdownlist供用户选择父级。 这是我的表定义:
Id Integer
ParentId_Fk Integer
Body Varchar
Title Varchar
创建页面视图:
@model MVCDrLaptop.Models.Education
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Create</title>
</head>
<body>
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<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>Education</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Text)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
<div class="editor-field">
//here is for parentId_FK DropDownList
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
那么我应该写什么来创建我的DropDownList?
答案 0 :(得分:3)
@Html.DropDownListFor
然后从模型中应用您需要的字段。
以下是使用DropDownList和DropDownListFor http://blinkingcaret.wordpress.com/2012/08/11/using-html-dropdownlistfor/
的示例答案 1 :(得分:3)
首先从数据库中获取所有值。
控制器:
IEnumerable<SelectListItem> items = from value in values
select new SelectListItem
{
Text = value.ToString(),
Value = value.ToString(),
Selected = value == selectedMovie,
};
ViewBag.MovieType = items;
查看:
@Html.DropDownList("items")