渲染,然后从MVC3下拉列表中的数据 [英] render and select data from mvc3 DropDown list
本文介绍了渲染,然后从MVC3下拉列表中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简单的情况
一个目标用户有很多的用户组。
我要实现对MVC3表单编辑或创建行动,从下拉群组。
控制器:
私人列表<使用者> GetAllUsers()
{
清单<使用者>用户;
用户=找到所有用户列表...
回报用户;
}公众的ActionResult编辑(GUID标识)
{
ViewBag.UserGroups =新的SelectList(GetAllUsers(),用户ID,名称);
返回查看();
}
查看:
< DIV CLASS =编辑标记>
@ Html.LabelFor(型号=> model.UserGroupId,UserGroupId)
< / DIV>
< DIV CLASS =主编场>
@ Html.DropDownList(放什么吗?);
@ Html.ValidationMessageFor(型号=> model.UserGroupId)
< / DIV>
解决方案
哦,请使用视图模型,切ViewBag的废话,让我感到恶心我每次看到它的时间。
公共类UserViewModel
{
公众诠释UserGroupId {搞定;组; }
公共IEnumerable的< SelectListItem>群组{搞定;组; }
}
和则:
公众的ActionResult编辑(GUID标识)
{
VAR模型=新UserViewModel
{
群组=新的SelectList(GetAllUsers(),用户ID,名称)
}
返回查看(模型);
}
和视图:
@model UserViewModel
...
< DIV CLASS =编辑标记>
@ Html.LabelFor(型号=> model.UserGroupId,UserGroupId)
< / DIV>
< DIV CLASS =主编场>
@ Html.DropDownListFor(X => x.UserGroupId,Model.UserGroups);
@ Html.ValidationMessageFor(型号=> model.UserGroupId)
< / DIV>
< / DIV>
但如果你想要让我恶心,保持ViewCrap:
@ Html.DropDownListFor(
X => x.UserGroupId,
(IEnumerable的< SelectListItem>)ViewBag.UserGroups
)
Simple situation
One object User have many UserGroups.
I want to implement on mvc3 form editing or creating action to select UserGroups from drop down.
Controller:
private List<User> GetAllUsers()
{
List<User> users;
users = find all users to List...
return users;
}
public ActionResult Edit(Guid Id)
{
ViewBag.UserGroups = new SelectList(GetAllUsers(), "UserId", "Name");
return View();
}
View:
<div class="editor-label">
@Html.LabelFor(model => model.UserGroupId, "UserGroupId")
</div>
<div class="editor-field">
@Html.DropDownList(WHAT TO PUT HERE ?);
@Html.ValidationMessageFor(model => model.UserGroupId)
</div>
解决方案
Oh please use a view model, cut that crap of a ViewBag, makes me sick every time I see it.
public class UserViewModel
{
public int UserGroupId { get; set; }
public IEnumerable<SelectListItem> UserGroups { get; set; }
}
and then:
public ActionResult Edit(Guid Id)
{
var model = new UserViewModel
{
UserGroups = new SelectList(GetAllUsers(), "UserId", "Name")
}
return View(model);
}
and in the view:
@model UserViewModel
...
<div class="editor-label">
@Html.LabelFor(model => model.UserGroupId, "UserGroupId")
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.UserGroupId, Model.UserGroups);
@Html.ValidationMessageFor(model => model.UserGroupId)
</div>
</div>
but if you wanna make me sick and keep the ViewCrap:
@Html.DropDownListFor(
x => x.UserGroupId,
(IEnumerable<SelectListItem>)ViewBag.UserGroups
)
这篇关于渲染,然后从MVC3下拉列表中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文