简体   繁体   English

MVC下拉列表设置所选值

[英]MVC dropdownlist set selected value

Hey I have tried following to set the selected value for dropdownlist. 嗨,我尝试按照以下设置下拉列表的选定值。 In 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"})

But still not working, I did not got the selected value. 但是仍然无法正常工作,我没有获得所选的值。 When debugging I can see that Model.role.Id contains the selected value. 调试时,我可以看到Model.role.Id包含选定的值。

Note also that the Id is of type string, because it is hashed. 还要注意,Id是字符串类型的,因为它是经过哈希处理的。 What I am doing wrong? 我做错了什么?

There are few ways of display DropDownList in MVC. 在MVC中有几种显示DropDownList的方法。 I like the following approach. 我喜欢以下方法。

Note: You need a collection of SelectListItem in model. 注意:您需要模型中的SelectListItem的集合。

Model 模型

public class MyModel
{
    public int SelectedId { get; set; }
    public IList<SelectListItem> AllItems { get; set; }

    public MyModel()
    {
        AllItems = new List<SelectListItem>();
    }
}

Controller 调节器

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();
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM