MVC下拉列表设置选定值

本文关键字:设置 下拉列表 MVC | 更新日期: 2023-09-27 18:13:41

嘿,我已经尝试以下设置下拉列表的选定值。在My controller中:

u.Roles = new List<AspNetRole>();
foreach (var role in db.AspNetRoles)
{
    u.Roles.Add(role);
}

And in my View:

 @Html.DropDownList(Model.role.Id, new SelectList(Model.Roles, "Id", "Name"), htmlAttributes: new { @class = "form-control"})

但仍然不工作,我没有得到选择的值。当调试时,我可以看到Model.role.Id包含选定的值。

还要注意Id的类型是字符串,因为它是散列的。我做错了什么?

MVC下拉列表设置选定值

在MVC中有几种显示下拉列表的方法。我喜欢下面的方法。

注意:在model.

中需要一个SelectListItem的集合。

public class MyModel
{
    public int SelectedId { get; set; }
    public IList<SelectListItem> AllItems { get; set; }
    public MyModel()
    {
        AllItems = new List<SelectListItem>();
    }
}
h2控制器

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();
    }
}
<<h2>视图/h2>
@model DemoMvc.Controllers.MyModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.DropDownListFor(x => x.SelectedId, Model.AllItems)
    <input type="submit" value="Submit" />
}