[英]MVC dropdownlist set selected value
嗨,我尝试按照以下设置下拉列表的选定值。 在我的控制器中:
u.Roles = new List<AspNetRole>();
foreach (var role in db.AspNetRoles)
{
u.Roles.Add(role);
}
在我看来:
@Html.DropDownList(Model.role.Id, new SelectList(Model.Roles, "Id", "Name"), htmlAttributes: new { @class = "form-control"})
但是仍然无法正常工作,我没有获得所选的值。 调试时,我可以看到Model.role.Id
包含选定的值。
还要注意,Id是字符串类型的,因为它是经过哈希处理的。 我做错了什么?
在MVC中有几种显示DropDownList的方法。 我喜欢以下方法。
注意:您需要模型中的SelectListItem的集合。
public class MyModel
{
public int SelectedId { get; set; }
public IList<SelectListItem> AllItems { get; set; }
public MyModel()
{
AllItems = new List<SelectListItem>();
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel();
model.AllItems = new List<SelectListItem>
{
new SelectListItem { Text = "One", Value = "1"},
// *** Option two is selected by default ***
new SelectListItem { Text = "Two", Value = "2", Selected = true},
new SelectListItem { Text = "Three", Value = "3"}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Get the selected value
int id = model.SelectedId;
return View();
}
}
@model DemoMvc.Controllers.MyModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownListFor(x => x.SelectedId, Model.AllItems)
<input type="submit" value="Submit" />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.