【问题标题】:generate dropdownlist from a table in database从数据库中的表生成下拉列表
【发布时间】:2013-06-14 12:32:01
【问题描述】:

我试图更准确地回答我之前的问题,可以在这里找到,我得到了一些很好的答案,但不知道如何在我的情况下使用它Previous question 我得到了一些不错的答案,但无法弄清楚如何在我的情况下使用它。

基本上我想要一个包含

的注册页面
  1. Email //来自我的 AspNetUser(datamodel) 类,AspNetUsers 表也存在于数据库中。
  2. UserName//来自我的 AspNetUser(datamodel) 类,AspNetUsers 表也存在于数据库中。
  3. Password//来自我的 AspNetUser(datamodel) 类,AspNetUsers 表也存在于数据库中。
  4. Role//dropdownlist,来自Role(datamodel)类,数据库中也存在Roles表

在我的控制器中,我通过以下方式实现了我的 Register 方法:

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

在我的 get 方法中,我将 roles 传递给查看,现在我使用 AspNetUser 作为视图中的模型

@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("Login", "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 no how to generate dropdownlist)

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

你能告诉我如何获得dropdownlist 以及如何将选定的值传递给控制器​​以使用它,以便我可以在注册期间将用户置于角色?为注册创建新模型会更好吗?

编辑:AspNetUser 模型

  public class AspNetUser
    {
        private ICollection<Role> _roles= new Collection<Role>();
        public Guid Id { get; set; }

        [Required]
        public virtual String Username { get; set; }

        public virtual String Email { get; set; }

        [Required, DataType(DataType.Password)]
        public virtual String Password { get; set; }

        public virtual String FirstName { get; set; }
        public virtual String LastName { get; set; }

        [DataType(DataType.MultilineText)]
        public virtual String Comment { get; set; }

        public virtual Boolean IsApproved { get; set; }
        public virtual int PasswordFailuresSinceLastSuccess { get; set; }
        public virtual DateTime? LastPasswordFailureDate { get; set; }
        public virtual DateTime? LastActivityDate { get; set; }
        public virtual DateTime? LastLockoutDate { get; set; }
        public virtual DateTime? LastLoginDate { get; set; }
        public virtual String ConfirmationToken { get; set; }
        public virtual DateTime? CreateDate { get; set; }
        public virtual Boolean IsLockedOut { get; set; }
        public virtual DateTime? LastPasswordChangedDate { get; set; }
        public virtual String PasswordVerificationToken { get; set; }
        public virtual DateTime? PasswordVerificationTokenExpirationDate { get; set; }

        public virtual ICollection<Role> Roles
        {
            get { return _roles; }
            set { _roles = value; }
        }

    }

【问题讨论】:

    标签: asp.net-mvc-4 drop-down-menu model controller html.dropdownlistfor


    【解决方案1】:

    您最好有一个专门为此视图设计的视图模型。想想你在视图中需要什么信息并定义你的视图模型:

    public class RegisterViewModel
    {
        public string Email { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string SelectedRole { get; set; }
        public IEnumerable<SelectListItem> Roles { get; set; }
    }
    

    正如您从这个视图模型中看到的那样,为了拥有一个下拉列表,您需要 2 个属性:一个保存选定值的标量属性和一个保存可用值列表的集合属性。

    然后:

    public ActionResult Register()
    {
        string [] roles = Roles.GetAllRoles();
        var model = new RegisterViewModel();
        model.Roles = roles.Select(r => new SelectListItem 
        {
            Value = r,
            Text = r,
        });
        return View(model);
    }
    
    [HttpPost]
    public ActionResult Register(RegisterViewModel model)
    {
        // the model.SelectedRole will contain the selected value from the dropdown
        // here you could perform the necessary operations in order to create your user
        // based on the information stored in the view model that is passed
    
        // NOTE: the model.Roles property will always be null because in HTML,
        // a <select> element is only sending the selected value and not the entire list.
        // So if you intend to redisplay the same view here instead of redirecting
        // makes sure you populate this Roles collection property the same way we did 
        // in the GET action
    
        return Content("Thanks for registering");
    }
    

    最后是相应的视图:

    @model RegisterViewModel
    @{
        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("Login", "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(model => model.SelectedRole, Model.Roles)
            </div>
    
            <button class="btn btn-large btn-primary" type="submit">Sign In</button>
        }
    </div>
    

    【讨论】:

    • 谢谢!!你的回答简直太棒了。如果在我的 AspNetUser 类 public virtual ICollection&lt;Role&gt; Roles { get { return _roles; } set { _roles = value; } } 中添加这个会更好,其中 _roles 被设置为 ICollection&lt;Role&gt; = new Collection&lt;Role&gt;();
    • 我不知道你说的这个AspNetUser是什么。只有视图模型应该传递给视图。
    • 我在编辑中添加了我的 AspNetUser 类。基于这个类,将它作为模型传递给视图会很好,还是你仍然建议注册模型?我的意思是,如果我在我的 httpPost 方法中使用 AspNetUser 或者我应该坚持使用基于视图的注册模型,这可能是个好主意吗?可能是我没有正确理解事情。
    • 您应该始终使用视图模型。控制器操作仅将视图模型传入/传出视图。据我所知,这个 AspNetUser 类是一些只应该由您的服务层使用的域模型。对于特定的寄存器视图,它有无数无用的东西。
    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2011-11-09
    • 2021-10-31
    • 2014-12-25
    • 1970-01-01
    相关资源
    最近更新 更多