我如何使用的DropDownList在ASP.NET MVC 3 [英] How do I use the DropDownList in ASP.NET MVC 3
问题描述
我是新来的MVC,我试图填充在我看来,一个DropDownList与从我的控制器的规则列表。当我做上市的方式,我只是得到了一堆说CellularAutomata.Models.Rules项目的一个DropDownList。我知道我错误地这样做,我只是想知道我是如何真正得到它显示在DropDownList每个规则的规则描述。
我有一个模型
公共类规则
{
公众诠释ID {搞定;组; }
公众诠释名称{;组; }
公共字符串描述{搞定;组; } 公共规则(INT名,字符串描述)
{
名称=名称;
说明=描述; }
公共规则()
{
名= 0;
说明=;
}
}
一个控制器
公众的ActionResult指数()
{
从db.Rules规则VAR规则=
选择规则; 返回查看(rules.ToList());
}
和视图
@model IEnumerable的< CellularAutomata.Models.Rule>@ {
ViewBag.Title =指数;
}
< H2>指数< / H><表>
&所述; TR>
&所述; TD>
@ Html.DropDownList(测试,新的SelectList(型号))
< / TD>
< / TR>
< /表>
您可以有一个视图模型:
公共类MyViewModel
{
公共字符串SelectedRuleId {搞定;组; }
公共IEnumerable的<规则>规则{搞定;组; }
}
,然后在你的控制器:
公众的ActionResult指数()
{
VAR模型=新MyViewModel
{
规则= db.Rules
};
返回查看(模型);
}
和视图:
@model CellularAutomata.Models.MyViewModel
@ {
ViewBag.Title =指数;
}
< H2>指数< / H>@ Html.DropDownListFor(
X => x.SelectedRuleId,
新的SelectList(Model.Rules,ID,说明)
)
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>
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")
)
这篇关于我如何使用的DropDownList在ASP.NET MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!