我一直在下面的教程this這表明你如何填充一個下拉列表。但是我創建頁面不顯示一個下拉列表中所有,但顯示了這個MVC實體框架我的DropDownList不是一個下拉列表
這是我的下拉我UserController.cs列表代碼
private void PopulateAdministratorsDropDownList(object selectedAdministrator = null)
{
var administratorQuery = from d in db.Administrators
orderby d.AdministratorTitle
select d;
ViewBag.AdministratorID = new SelectList(administratorQuery, "AdministratorID", "AdministratorTitle", selectedAdministrator);
}
瀏覽\用戶\創建.cshtml
@model RecreationalServicesTicketingSystem.Models.User
....
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
.... // more controls
<div class="editor-label">
@Html.LabelFor(model => model.AdministratorID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.AdministratorID)
@Html.ValidationMessageFor(model => model.AdministratorID)
</div>
....
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
UserController.cs
public ActionResult Create()
{
PopulateAdministratorsDropDownList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "LastName, FirstMidName, EnrollmentDate,AdministratorID, DepartmentID, DepotID")]User user)
{
try
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
PopulateAdministratorsDropDownList(user.AdministratorID);
return View(user);
}
private void PopulateAdministratorsDropDownList(object selectedAdministrator = null)
{
var administratorQuery = from d in db.Administrators
orderby d.AdministratorTitle
select d;
ViewBag.AdministratorID = new SelectList(administratorQuery, "AdministratorID", "AdministratorTitle", selectedAdministrator);
}
將其更改爲'@ Html.DropDownListFor(M => m.AdministratorID,(的SelectList)ViewBag.AdministratorList)' - 不是你需要改變'ViewBag'屬性的名稱 - 它不能是相同的名稱屬性的結合。 –
'@ Html.DropDownListFor(型號=> model.AdministratorID,(的SelectList)ViewBag.AdministratorID)' –
還請注意,沒有一點的'SelectList'構造函數添加的最後一個參數('selectedAdministrator') - 由它忽略綁定到模型屬性時的HtmlHelper。 –