我有一个实体,让我们说Person
:
class Person
{
id Id { get; set; }
string Name { get; set; }
int RoleId { get; set; }
}
此RoleId属性对应于从可用角色列表中选择的角色。我使用ViewData对象将此角色列表传递给视图:
List<SelectListItem> roles = new List<SelectListItem>()
{
new SelectListItem(){ Text = "User", Value = "0"},
new SelectListItem(){ Text = "Admin", Value = "1"}
};
ViewData["roles"] = roles;
(注意我在这里使用字符串作为值,因为它不允许我使用整数?)
我的视图(它是一个“添加”视图,用于创建一个新的Person)继承自Person实体。我不确定如何在视图中设置下拉列表,以便列表中所选项的值被设置为发送回Controller的Person对象中的RoleId属性值(对于HttpPost方法)。
答案 0 :(得分:2)
<%= Html.DropDownList(
"RoleId",
new SelectList(ViewData["roles"] as IEnumerable<SelectListItem>, "Value", "Text")
) %>
据说这不是我推荐的代码。每当我看到有人使用ViewData,我的体温就会升高。
我会使用视图模型:
public class PersonViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string RoleId { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
}
然后在你的控制器中:
public ActionResult Index()
{
var model = new PersonViewModel
{
Roles = new[]
{
new SelectListItem { Text = "User", Value = "0" },
new SelectListItem { Text = "Admin", Value = "1" }
}
};
return View(model);
}
并在您的强类型视图中:
<%= Html.DropDownListFor(
x => x.RoleId,
new SelectList(Model.Roles, "Value", "Text")
) %>
答案 1 :(得分:2)
UPDATE :Andy,关于为什么不能使用int的问题,这是因为HTML对类型没有任何了解,只知道字符串。但是,如下所述,MVC模型绑定器将查看RoleId属性(它是一个int)并尝试为您进行转换。如果您在那里传递说“one”,则模型绑定将失败。
我认为这里有两件事要理解:
首先,电话:
@Html.DropDownList("DropDowListId", (List<SelectListItem>)this.ViewData["roles"], "Select a role...")
产生
<select id="DropDowListId" name="DropDowListId">
<option value="">Select a role...</option>
<option value="0">User</option>
<option value="1">Admin</option>
</select>
这会产生一个FORM帖子(假设名称为Joe,角色为Admin),其中包含以下内容:
Name=Joe&DropDowListId=1
现在,假设你的帖子方法是:
[HttpPost]
public ActionResult Create(Person person)
模型绑定器可以将Name映射到person,但不知道如何处理DropDownListId(它不是Person模型的一部分)。
因此,如果您将DropDownList的名称更改为Person类中的RoleId:
@Html.DropDownList("RoleId", (List<SelectListItem>)this.ViewData["roles"], "Select a role...")
将产生:
<select id="RoleId" name="RoleId">
<option value="">Select a role...</option>
<option selected="selected" value="0">User</option>
<option value="1">Admin</option>
</select>
注意,您实际上也会获得额外的验证信息(如下所示:data-val =“true”data-val-number =“字段RoleId必须是数字。”data-val-required =“RoleId字段是必需的。“)
现在,当帖子发生时,表单将包含以下内容:
Name=Joe&RoleId=1
模型绑定器能够绑定到您的类。现在,Person将包含一个名称:Joe,RoleId:1。字符串'1'甚至将转换为int(或者,如果您使用字符串作为RoleId,它将保留为'1'的字符串。
很酷,嗯?