开发者

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

开发者 https://www.devze.com 2023-03-09 16:14 出处:网络
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.

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

精彩评论

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

关注公众号