简体   繁体   English

将 ViewBag 用于选择列表的正确方法

[英]Proper way to use ViewBag for selectlist

I am getting an error on my selectlist when I open the form.打开表单时,我的选择列表出现错误。 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot convert type 'System.Collections.Generic.List<System.Web.Mvc.SelectListItem>' to 'System.Web.Mvc.SelectList'' I have tried other ways of doing this but always get some error. Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot convert type 'System.Collections.Generic.List<System.Web.Mvc.SelectListItem>' to 'System.Web.Mvc.SelectList''我尝试了其他方法,但是总是得到一些错误。 The other way gave an error on submit.另一种方式提交时出错。 In this case it wont load the page.在这种情况下,它不会加载页面。

Here is my model.这是我的 model。

[Required(ErrorMessage = "The Roles is required")]
public string Role { get; set; }

This is my controller:这是我的 controller:

    public ActionResult RegisterUser()
    {
        RegisterViewModel objRegisterViewModel = new RegisterViewModel();
        ViewBag.Roles = GetAllRolesAsSelectList();

        return View(objRegisterViewModel);
    }

The rest of the controller Action: controller动作的rest:

    private List<SelectListItem> GetAllRolesAsSelectList()
    {
        List<SelectListItem> SelectRoleListItems =
            new List<SelectListItem>();

        var roleManager =
            new RoleManager<IdentityRole>(
                new RoleStore<IdentityRole>(new ApplicationDbContext()));

        var colRoleSelectList = roleManager.Roles.OrderBy(x => x.Name).ToList();

        foreach (var item in colRoleSelectList)
        {
            if (User.IsInRole("Administrator"))
            {
                SelectRoleListItems.Add(
                            new SelectListItem
                            {
                                Text = item.Name.ToString(),
                                Value = item.Name.ToString()
                            });

            }
            else
            {
                if (item.Name != "Administrator")
                {
                    SelectRoleListItems.Add(
                            new SelectListItem
                            {
                                Text = item.Name.ToString(),
                                Value = item.Name.ToString()
                            });
                }
            }

        }

        return SelectRoleListItems;
    }

Here is the View:这是视图:

  @Html.DropDownList("Role", (SelectList)ViewBag.Roles, "Select Role", new { @class = "form-control" })

Thanks for your help, any will be appreciated.感谢您的帮助,我们将不胜感激。

UPDATE: I tried changing this as follows:更新:我尝试按如下方式更改:

 ViewBag.Roles = context.Roles.Select(b => new SelectListItem { Value = b.Name, Text = b.Name });

Model: Model:

[Required(ErrorMessage = "The Roles is required")]
public string Role { get; set; }

View:看法:

     @Html.DropDownListFor(m => m.Role, ViewBag.Roles as SelectList, "--Select Role--", new { @class = "form-control" })

Now getting an error System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Role'.'现在出现错误System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Role'.'

Role is a string.角色是一个字符串。 I have tried using public IEnumerable<SelectListItem> UserRoles { get; set; }我试过使用public IEnumerable<SelectListItem> UserRoles { get; set; } public IEnumerable<SelectListItem> UserRoles { get; set; } public IEnumerable<SelectListItem> UserRoles { get; set; } And can get it to load but when I submit the form it errors that the Role is required. public IEnumerable<SelectListItem> UserRoles { get; set; }可以让它加载但是当我提交表单时它错误地指出角色是必需的。 List is there and then disappears on submit.列表在那里,然后在提交时消失。 So it looses the selected value.所以它失去了选择的价值。

UPDATE:更新:

I have followed this tutorial, it is what I originally used before.我已经遵循了这个教程,它是我以前使用的。 Asp.net mvc 5 Asp.net MVC 5

I am still getting this error: System.InvalidOperationException: 'The ViewData item that has the key 'UserRoles' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.'我仍然收到此错误: System.InvalidOperationException: 'The ViewData item that has the key 'UserRoles' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.' Makes no sense I have used this before with no issues.毫无意义我以前用过这个没有问题。

First, you need to add an Id to your Model Model will be like this首先,你需要给你的 Model 添加一个 Id Model 会像这样

 [Required(ErrorMessage = "The Roles is required")]
 public string Role { get; set; }

 public long Id {get; set;}

and then in Controller, you need to get the data from DB然后在Controller,需要从DB中获取数据

List<Roles> roles = _context.Roles.ToList();

now we can make a ViewBag like this现在我们可以像这样制作一个 ViewBag

ViewBag.ListOfRoles = new SelectList(roles, "Id", "Role");

After the in View, you have too many ways to display Select, but I prefer this way in View之后,Select的显示方式太多了,但我更喜欢这种方式

<select asp-items="@ViewBag.ListOfRoles" asp-for="Id">
       <option selected disabled>--Select--</option>
 </select>

Note that asp-items means the item to display in select注意, asp-items表示要在 select 中显示的项目
and asp-for refers to the ModelVM in your page, it must refer to an Id to make sense or maybe it will be like something like this RoleId并且asp-for指的是您页面中的ModelVM ,它必须引用一个Id才有意义,或者它可能会像这样的RoleId

I hope it's clear now.我希望现在一切都清楚了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM