我一直在用這個HTML Helper放屁一段時間,遵循各種理論上完成相同的最終結果的例子。然而,我似乎無法產生最終結果...DropDownListFor()幫助請
也許有人可以看到我做錯了之前,我回到迭代選擇與foreach選項。鎖定這個幫助程序的工作方式是很好的,而不是使用foreach()選擇的代碼。提前致謝。
編輯控制器;
public ActionResult Edit(string id)
{
if (id != "")
{
UserViewModel user = (from u in db.Users.Where(u => u.Id.Equals(id))
from ur in u.Roles
join r in db.Roles on ur.RoleId equals r.Id
select new UserViewModel
{
UserId = u.Id,
DisplayName = u.DisplayName,
Role = r.Name,
RoleId = r.Id
}
).FirstOrDefault();
//Select List items for select list
var roles = db.Roles.Select(r => new SelectListItem { Value = r.Id, Text = r.Name });
//select list with selected value
user.Roles = new SelectList(roles,"Value", "Text", user.RoleId);
return View(user);
}
return View();
}
查看;
<div class="form-group">
@Html.LabelFor(model => model.Role, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Role, Model.Roles, null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Role, "", new { @class = "text-danger" })
</div>
</div>
問題是什麼?和預期的結果是什麼,你提到 –