如何请求列表来自控制器的数据或任何其他数据
我需要渲染一个下拉列表,但我不想将列表的值作为模型的一部分传递给视图。
基本上我想做的事情看起来像这样:
@{
var roles = Html.Action("GetRoles");
var selectList = from r in roles select new SelectListItem
{
Selected = (r.Id == Model.DefaultRole.Id),
Text = r.RoleName,
Value = r.Id.ToString(),
};
}
@Html.DropDownList("roles", selectList)
@Html.ValidationMessageFor(m => m.DefaultRole)
和操作方法
public List<aspnet_Role> GetRoles()
{
return _dataContext.GetAspnetRoles();
}
当然,这是行不通的。我该怎么做呢?
I need to render a DropDown list and I don't want to pass list's values to the View as a part of the model.
Basically what I'm trying to do looks like that:
@{
var roles = Html.Action("GetRoles");
var selectList = from r in roles select new SelectListItem
{
Selected = (r.Id == Model.DefaultRole.Id),
Text = r.RoleName,
Value = r.Id.ToString(),
};
}
@Html.DropDownList("roles", selectList)
@Html.ValidationMessageFor(m => m.DefaultRole)
And the action method
public List<aspnet_Role> GetRoles()
{
return _dataContext.GetAspnetRoles();
}
Of course that wouldn't work. How should I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将其放入 ViewBag 中。在你的控制器中,你可以这样做:
然后在你的视图中,只需将你的 DropDownList 更改为:
ViewBag 是一个动态类型的“东西”持有者,你几乎可以将任何东西粘在那里。 :) 它的目的是将不属于模型一部分的东西传递给视图。
Put it in the ViewBag. In your controller you can do this:
Then in your View simply change your DropDownList to this:
ViewBag is a dynamically typed holder of "stuff", you can stick almost anything in there. :) It's meant to pass things to a view that aren't part of the model.