How do I use the DropDownList in ASP.NET MVC 3
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&开发者_Python百科gt;
<table>
<tr>
<td>
@Html.DropDownList("Test", new SelectList(Model))
</td>
</tr>
</table>
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")
)
精彩评论