如何在 @Html.DropDownListFor 中显示角色名称而不是其 id

本文关键字:id 角色 @Html DropDownListFor 显示 | 更新日期: 2023-09-27 18:33:30

我有一个取消注册表单,我必须选择用户角色(管理员或用户),但我不知道如何在下拉列表中显示角色的名称而不是 id。

我的控制器是:

public ActionResult Register()
{
    CDraguseniDBEntities dbContext = new CDraguseniDBEntities();
    IEnumerable<SelectListItem> items = dbContext.Users.Select(c => new SelectListItem
    {              
        Value=c.RoleID,
        Text =c.RoleID.ToString()
    });
    ViewBag.RoleID = items;
    return View();
}

我的观点是:

@model ExamenBudescuMarius_2emeSes.Models.UserModel
@{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Register</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
    <legend>UserModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.RoleID)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.RoleID)
        @Html.ValidationMessageFor(model => model.RoleID)
    </div>
    <div>
        <p>Role ID</p>
        @Html.DropDownListFor(model => model.RoleID, ViewBag.RoleID as IEnumerable<SelectListItem>, "-Select a value-", new { @class = "dropDown" })
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Username)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Username)
        @Html.ValidationMessageFor(model => model.Username)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Password)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.ConfirmPassword)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ConfirmPassword)
        @Html.ValidationMessageFor(model => model.ConfirmPassword)
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

我的模型是:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CompareAttribute = System.Web.Mvc.CompareAttribute;
namespace ExamenBudescuMarius_2emeSes.Models
{
public class UserModel
{
    public int UserID { get; set; }
    public string Username { get; set; }
    [DataType(DataType.Password)]
    [StringLength(255, MinimumLength = 8)]
    public string Password { get; set; }
    [Required(ErrorMessage = "Your Name is required")]
    [StringLength(50, ErrorMessage = "Your name must be maximum 50 letters.")]
    [Remote("UsernameExists", "Account", HttpMethod = "POST", ErrorMessage = "User name already registered.")]
    [Display(Name = "Name")]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "Your Last Name is required")]
    [StringLength(70, ErrorMessage = "Your name must be max 70 letters.")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
    [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+'.[A-Za-z]{2,4}", ErrorMessage = "Email doesn't look like a valid email address.")]
    [Remote("EmailExists", "Account", HttpMethod = "POST", ErrorMessage = "Email address already registered.")]
    [Display(Name = "Email")]
    public string Email { get; set; }
    public int RoleID { get; set; }
    public virtual Roles Roles { get; set; }
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    [DataType(DataType.Password)]
    [StringLength(255, MinimumLength = 8)]
    public string ConfirmPassword { get; set; }
}

我的数据库表是:

CREATE TABLE Roles(
    RoleID int identity(1,1) Primary key not null,
    RoleName varchar(50) not null
);
create table Users(
    UserID int identity(1,1) primary key not null,
    Username varchar(100) not null,
    [Password] varchar(120) not null,
    FirstName varchar(120) not null,
    LastName varchar(120) not null,
    Email varchar(120) not null,
    RoleID int not null,
    CONSTRAINT [FK_RoleIDRoles] FOREIGN KEY ([RoleID]) REFERENCES [dbo].[Roles]     ([RoleID])
);
create table Album(
    AlbumID int identity(1,1)  primary key not null,
    AlbumName varchar(120) not null
);
create table Images(
    ImageID int identity(1,1) primary key not null,
    ImageName varchar(120) not null,
    ImagePath nvarchar(100) not null,
    ImageDescription varchar(max) ,
    AlbumID int,
    CONSTRAINT [FK_Images_Album] FOREIGN KEY ([AlbumID]) REFERENCES [dbo]. [Album] ([AlbumID])
);

如何在 @Html.DropDownListFor 中显示角色名称而不是其 id

首先,您应该查询 dbContext 的 Roles 集合以获取 Roles 列表。生成 items 集合时,获取RoleName并使用它来设置 SelectListItem 的 Text 属性。

var items = dbContext.Roles
                     .Select(c => new  SelectListItem
                                                     { 
                                                       Value = c.RoleID.ToString(),
                                                       Text = c.RoleName
                                                     });

我已经设法在我的下拉列表中显示了角色的名称,现在在我提交表单后,我收到 un 错误,例如:

具有键"RoleID"的 ViewData 项的类型为"System.Int32",但必须为"IEnumerable"类型。 Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle.Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code.

Détails de l'exception: System.InvalidOperationException: 具有键"RoleID"的 ViewData 项的类型为"System.Int32",但必须为"IEnumerable"。

错误来源:

 Ligne 24 :         <div>
 Ligne 25 :             <p>Role ID</p>
 Ligne 26 :               @Html.DropDownListFor(model => model.RoleID,     ViewBag.RoleList as SelectList, "-Select a value-", new { @class = "dropDown" })
 Ligne 27 :         </div>
 Ligne 28 : 
Fichier source : d:'ephec'2015-2016'Web côté client'ExamenBudescuMarius- 2emeSes'ExamenBudescuMarius-2emeSes'Views'Account'Register.cshtml    Ligne : 26

现在我的控制器看起来像:

   public ActionResult Register()
    {
        CDraguseniDBEntities dbContext = new CDraguseniDBEntities();
        UserModel um = new UserModel();
        IEnumerable<SelectListItem> items = new SelectList(dbContext.Roles, "RoleID", "RoleName", um.RoleID);
        ViewBag.RoleList = items;
 /* 
        IEnumerable<SelectListItem> items = dbContext.Roles.Select(c => new    SelectListItem
        {
            Text=c.RoleName,
        });
        ViewBag.RoleID = items;*/
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(UserModel U)
    {
        if (ModelState.IsValid)
        {
            using (CDraguseniDBEntities dc = new CDraguseniDBEntities())
            {
                var count = dc.Users.Count(use => use.Username == U.Username);
                //you should check duplicate registration here 
               if(count==0)
               {
                   Users user = new Users();
                   user.RoleID = U.RoleID;
                   user.FirstName = U.FirstName;
                   user.LastName = U.LastName;
                   user.Email = U.Email;
                   user.Username = U.Username;
                   user.Password = U.Password;
                   dc.Users.Add(user);
                   dc.SaveChanges();
                   ModelState.Clear();
                   U = null;
                   ViewBag.Message = "Successfully Registration Done";
               }
               else
               {
                   ViewBag.Message = "User already exist";
               }
            }
        }
        return View(U);
    }