ASP.net MVC的SelectList提交给美国所有角色 [英] ASP.net MVC SelectList filed with all roles

查看:263
本文介绍了ASP.net MVC的SelectList提交给美国所有角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让所有的角色都从我的数据库到选择列表。
这是我CONTROLER:

I'm trying to get All roles From my dataBase into select List. This my controler :

[AllowAnonymous]
public ActionResult Register()
{
    ViewBag.Roles = new SelectList(Roles.GetAllRoles(), "ROLEID", "ROLENAME");
    return View();
}

我的模型:

public List<SelectListItem> SelectedRoles { set; get; }

这是这是我的看法:

<div class="input-group">
   <label for="Centre">Roles(s)</label>
   @Html.ListBoxFor(m=>m.SelectedRoles, (ViewBag.Roles as SelectList), new { @class = "chosen-select", data_placeholder = "Agent(s)." })
   @Html.ValidationMessageFor(m=>m.SelectedRoles)
</div>

但我得到这个错误:

But I get this error :

有类型为IEnumerable的具有关键SelectedRoles'。没有ViewData的项目

There is no ViewData item of type 'IEnumerable' that has the key 'SelectedRoles'.

这是什么问题?

推荐答案

确定。我忘了一件事,更换ListBoxFor要ListBox中,像这样的:

Ok. I forgot one thing, replace ListBoxFor To ListBox, like this:

ViewBag.ListRoles = new SelectList(Roles.GetAllRoles(), "Id", "Name");

@Html.ListBox("SelectedRoles", (SelectList)ViewBag.ListRoles)

确保该名称不符合ViewBag类似

make sure that the names are not similar with ViewBag

修改

这不是一个更好的办法,但我认为作品。把里面的观点:

It's not a better way but i think works. Put inside View:

<select>
@foreach (var item in Roles.GetAllRoles())
{
    <option value="@item">@item</option>
}
</select>

这篇关于ASP.net MVC的SelectList提交给美国所有角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆