【问题标题】:Creating dropdownlist from values in database从数据库中的值创建下拉列表
【发布时间】:2013-06-14 21:41:06
【问题描述】:

我有一个名为 Roles 的表,其中包含三个字段

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

在我的register.cshtml 视图中,我想要一个dropdownlist,它显示Roles 表中的RoleName 列表。我还需要能够获得该值并使用它,例如将角色分配给用户,这将在控制器中完成。 我的视图目前如下所示,我将模型用作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();
        }

    }

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

【问题讨论】:

    标签: asp.net-mvc-4 drop-down-menu


    【解决方案1】:

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

    有很多方法可以实现这一点,但在您的 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,你很可能会使用 Html 助手DropDownListFor 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 })
    

    【讨论】:

    • 你能解释一下那个 IDbContext 类吗?我只需要添加一些命名空间来使用它吗?我需要为此创建一个类吗?
    • 这是一个虚构的接口,我添加它是因为我不确定您如何访问GetAllRoles() 方法。在我使用的 mvc 项目中,我有 IOC (en.wikipedia.org/wiki/Inversion_of_control) 连接我的控制器并为控制器提供它们所需的依赖项。我设想你会传入包含GetAllRoles() 方法的类。
    • GetAllRoles() 是否在您的控制器的单独类中?如果它在控制器而不是单独的类中,那么您不需要将参数传递给构造函数,但是如果您还没有,我会敦促您考虑将它放入不同的类中,这将帮助您您的应用程序 SOLID (en.wikipedia.org/wiki/SOLID_(object-oriented_design))
    • 实际上我使用默认 RoleProvider 来获取我拥有的角色列表。因此,Roles.GetAllRoles(); 为我获取了所有角色,即字符串数组。但在我看来,我将模型用作aspnetuser,它不知道Roles。那么如果我像在上面显示的控制器中那样传递角色,它将如何工作
    • 好的,在这种情况下,请参阅编辑 1
    【解决方案2】:

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

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

    在视图中:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 2015-12-15
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多