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

时间:2016-02-07 12:52:03

标签: c# asp.net-mvc-4

我有一个取消注册表单,我必须选择用户角色(管理员或用户),但我不知道如何在我的下拉列表中显示角色的名称而不是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])
);

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

  

具有键“RoleID”的ViewData项的类型为“System.Int32”,但必须是“IEnumerable”类型。   描述:Une例外非géréess'estproduite au moment de l'exécutiondelarequêteWebactuelle。 Contrôlezlatrace de la pile pour plus d'informations sur l'erreur et son origine dans le code。

     

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

Erreur来源:

 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);
    }