How do I use the DropDownList in ASP.NET MVC 3

雨燕双飞 提交于 2020-01-06 06:10:13

问题


I am new to MVC and am trying to populate a DropDownList in my view with a list of 'rules' from my controller. When I do it the way listed, I just get a dropdownlist with a bunch of items that say CellularAutomata.Models.Rules. I know I am doing this incorrectly, I'm just wondering how I actually get it to show the rule description for each rule in the dropdownlist.

I have a Model

public class Rule
{
    public int ID { get; set; }
    public int Name { get; set; }
    public string Description{ get; set; }

    public Rule(int name, string description)
    {
        Name = name;
        Description = description;

    }
    public Rule()
    {
        Name = 0;
        Description = "";
    }
}

A Controller

    public ActionResult Index()
    {
        var rules = from rule in db.Rules
                    select rule;

        return View(rules.ToList());
    }

And a view

@model IEnumerable<CellularAutomata.Models.Rule>

@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>

<table>
    <tr>
        <td>
            @Html.DropDownList("Test", new SelectList(Model))
        </td>
    </tr>
</table>

回答1:


You could have a view model:

public class MyViewModel
{
    public string SelectedRuleId { get; set; }
    public IEnumerable<Rule> Rules { get; set; }
}

and then in your controller:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        Rules = db.Rules
    };
    return View(model);
}

and in the view:

@model CellularAutomata.Models.MyViewModel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>

@Html.DropDownListFor(
    x => x.SelectedRuleId, 
    new SelectList(Model.Rules, "ID", "Description")
)


来源:https://stackoverflow.com/questions/5096204/how-do-i-use-the-dropdownlist-in-asp-net-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!