2

我有一个Roles包含三个字段的表

  1. Guid RoleId
  2. string RoleName
  3. string Description

在我register.cshtml看来,我想要一个dropdownlist显示表中 RoleName 的Roles列表。我还需要能够获得该值并使用它,例如将角色分配给用户,这将在控制器中完成。我的视图目前看起来像下面的视图,我使用的是模型,AspNetUser但它不Role知道我想在哪个视图中显示dropdownlist.

@model Sorama.CustomAuthentiaction.Models.AspNetUser
@{
    ViewBag.Title = "Register";
    Layout = "~/Views/shared/_BootstrapLayout.empty.cshtml";
}

@section Styles{
    <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
}
<div class ="form-signin">

    @using (Html.BeginForm("Register", "Account"))
    {
        @Html.ValidationSummary(true)
        <h2 class="form-signin-heading"> Register </h2>
        <div class ="input-block-level">@Html.TextBoxFor(model=>model.Email, new{@placeholder = "Email"})</div>
        <div class ="input-block-level">@Html.TextBoxFor(model=>model.UserName, new{@placeholder = "UserName"})</div>
        <div class ="input-block-level">@Html.PasswordFor(model=>model.Password, new{@placeholder ="Password"})</div>
        <div class ="input-block-level">@Html.DropDownListFor(//don't know what to do

        <button class="btn btn-large btn-primary" type="submit">Register</button>
    }
</div>

我的控制器看起来像这样

   public class AccountController : Controller
    {
        //private readonly IDbContext dbContext;
        //
        // GET: /Account/
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(LoginModel model)
        {
            if(Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        [HttpGet]
        public ActionResult Register()
        {
            string [] roles = Roles.GetAllRoles();
            return View(roles);
        }

        [HttpPost]
        public ActionResult Register(AspNetUser model)
        {

            return View();
        }

        public ActionResult Index()
        {
            return View();
        }

    }

我需要做什么才能拥有该下拉列表?

4

2 回答 2

2

在您的控制器中,您需要以某种方式将代表您的角色的string[]( ) 传递到您的视图中......IEnumerable<string>

有很多方法可以实现这一点,但在您的 AccountController 中,您可以执行以下操作:

public class AccountController : Controller
{
   private IDbContext dbContext;

   public AccountController(IDbContext dbContext)
   {
       // Made up field that defines your GetAllRoles method
       this.dbContext = dbContext;
   }

   public ActionResult Register()
   {
      // Call the GetAllRoles() and capture the result in a variable called roles
      var roles = dbContext.GetAllRoles();

      return View(new AspNetUser {
         Roles = roles
      });
   }
}

注意:我不强制列表在控制器中以任何形式出现(我没有指定它应该是一个选择列表),我可能希望以不同的方式显示项目,并且我通过传递让视图变得灵活仅值并允许视图决定如何呈现值。

然后,在您的视图中,您可以使用您希望下拉列表出现的位置:

@Html.DropDownListFor(model => model.Roles, Model.Roles
    .Select(role => new SelectListItem { Text = role, Value = role })

正如我所提到的,有很多方法可以实现您想要的,但几乎有一件事是肯定的,即使用 aspnet mvc 您很可能会在DropDownListFor此处使用 Html 助手 MSDN 文档:

http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlistfor(v=vs.108).aspx

编辑1:

创建一个模型来保存用户和角色信息,如下所示:

public class RegisterViewModel
{
   public AspNetUser AspNetUser { get; set; }
   public IEnumerable<string> Roles { get; set; }
}

在控制器中,它可能看起来像这样:

public class AccountController : Controller
{
   private RoleProvider roleProvider;

   public AccountController(RoleProvider roleProvider)
   {
       this.roleProvider = roleProvider;
   }

   public ActionResult Register()
   {
      // Call the GetAllRoles() and capture the result in a variable called roles
      // var roles = roleProvider.GetAllRoles();

      // Or, as you have specified:
      var roles = Roles.GetAllRoles();

      return View(new RegisterViewModel {
         AspNetUser = GetTheAspNetUser(),
         Roles = roles
      });
   }
}

在视图中,您需要更新要使用的模型:

@model Sorama.CustomAuthentiaction.Models.RegisterViewModel

如果您不愿意/无法进行此类更改,您可以将角色列表添加到 Viewbag:

ViewBag.RoleList = roleProvider.GetAllRoles();

或者正如你所提到的:

ViewBag.RoleList = Roles.GetAllRoles();

然后像这样在视图中访问:

@Html.DropDownListFor(model => model.Roles, ViewBag.RoleList
    .Select(role => new SelectListItem { Text = role, Value = role })
于 2013-06-14T08:54:35.637 回答
2

在类似的情况下,我做了这样的事情:

private void BagSelectList()
{
    ViewBag.List = new SelectList(
            db.SetOfCandidateValues, 
            "KeyPropertyOfTheSet", 
            "NameOfThePropertyToAppearInTheDropDownList", 
            selectedValue);
}

在视图中:

@Html.DropDownListFor(
            model => model.ForeignKeyProperty, 
            (SelectList)ViewBag.List)

(当然,如果你不喜欢ViewBag,你可以使用强类型视图模型。)

于 2013-06-14T08:56:59.337 回答