开发者

How to request List<T> data or any other data from the Controller

I need to render a DropDown 开发者_JAVA技巧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?


Put it in the ViewBag. In your controller you can do this:

ViewBag.selectList = from r in roles select new SelectListItem
                 {
                     Selected = (r.Id == Model.DefaultRole.Id),
                     Text = r.RoleName,
                     Value = r.Id.ToString(),
                 };

Then in your View simply change your DropDownList to this:

@Html.DropDownList("roles", ViewBag.selectList)

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜