MVC dropdownlist 设置所选值

嘿,我尝试了以下内容来设置所选值 dropdownlist.
在我的控制器中:


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

包含所选值。

还要注意标识符具有类型 string, 因为他是harse。
我究竟做错了什么?
</aspnetrole>
已邀请:

郭文康

赞同来自:

有几种方法可以显示。 DropDownList 在 MVC. 我喜欢下一个方法。

注意:您需要一个集合

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 =&gt; x.SelectedId, Model.AllItems/
<input type="submit" value="Submit"/>
}


</selectlistitem></selectlistitem></selectlistitem>

要回复问题请先登录注册