Asp.net mvc 4 从数据库中的表生成dropdownlist

Asp.net mvc 4 从数据库中的表生成dropdownlist,asp.net-mvc-4,drop-down-menu,model,controller,html.dropdownlistfor,Asp.net Mvc 4,Drop Down Menu,Model,Controller,Html.dropdownlistfor,我试图更精确地回答我的前一个问题,可以在这里找到,我得到了一些很好的答案,但不知道如何在我的情况下使用它 我得到了一些很好的答案,但不知道如何在我的情况下使用它 基本上我想有一个注册页面,其中包含 Email//来自我的AspNetUser(datamodel)类,数据库中也存在AspNetUsers表 UserName//来自我的AspNetUser(datamodel)类,数据库中也存在AspNetUsers表 Password//来自我的AspNetUser(datamodel)类,数据库

我试图更精确地回答我的前一个问题,可以在这里找到,我得到了一些很好的答案,但不知道如何在我的情况下使用它 我得到了一些很好的答案,但不知道如何在我的情况下使用它

基本上我想有一个注册页面,其中包含

  • Email
    //来自我的AspNetUser(datamodel)类,数据库中也存在AspNetUsers表
  • UserName
    //来自我的AspNetUser(datamodel)类,数据库中也存在AspNetUsers表
  • Password
    //来自我的AspNetUser(datamodel)类,数据库中也存在AspNetUsers表
  • Role
    //dropdownlist,来自Role(datamodel)类,数据库中也存在Roles表
  • 在我的控制器中,我以以下方式执行了我的
    寄存器
    方法:

    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方法中,我将
    角色
    传递给view,现在我使用
    AspNetUser
    作为view中的模型

    @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>
    

    您最好有一个专门为此视图设计的视图模型。考虑视图中需要哪些信息,并定义视图模型:

    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; }
    }
    
    公共类RegisterViewModel
    {
    公共字符串电子邮件{get;set;}
    公共字符串用户名{get;set;}
    公共字符串密码{get;set;}
    公共字符串SelectedRole{get;set;}
    公共IEnumerable角色{get;set;}
    }
    
    从该视图模型中可以看到,要获得下拉列表,您需要两个属性:一个标量属性用于保存选定值,另一个集合属性用于保存可用值列表

    然后:

    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");
    }
    
    public ActionResult寄存器()
    {
    字符串[]角色=角色。GetAllRoles();
    var model=new RegisterViewModel();
    model.Roles=Roles.Select(r=>newselectListItem
    {
    值=r,
    Text=r,
    });
    返回视图(模型);
    }
    [HttpPost]
    公共操作结果寄存器(RegisterViewModel模型)
    {
    //model.SelectedRole将包含从下拉列表中选择的值
    //在这里,您可以执行必要的操作来创建您的用户
    //基于存储在传递的视图模型中的信息
    //注意:model.Roles属性将始终为null,因为在HTML中,
    //元素仅发送选定值,而不是整个列表。
    //因此,如果您打算在此处重新显示相同的视图,而不是重定向
    //确保以与我们相同的方式填充此角色集合属性
    //在行动中
    返回内容(“感谢注册”);
    }
    
    最后是相应的观点:

    @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>
    
    @model RegisterViewModel
    @{
    ViewBag.Title=“寄存器”;
    Layout=“~/Views/shared/\u BootstrapLayout.empty.cshtml”;
    }
    @剖面样式{
    }
    @使用(Html.BeginForm(“登录”、“帐户”))
    {
    @Html.ValidationSummary(true)
    登记
    @Html.TextBoxFor(model=>model.Email,新的{placeholder=“Email”})
    @Html.TextBoxFor(model=>model.UserName,新的{placeholder=“UserName”})
    @Html.PasswordFor(model=>model.Password,新的{placeholder=“Password”})
    @DropdownlistFor(model=>model.SelectedRole,model.Roles)
    登录
    }
    
    谢谢!!你的答案简直太棒了。如果在我的AspNetUser类
    公共虚拟ICollection角色{get{return{u Roles;}set{{u Roles=value;}}
    中添加这个会更好吗?其中{u角色被设置为
    ICollection=new Collection()
    我不知道你说的这个
    AspNetUser
    是什么。只应将视图模型传递给视图。我已在编辑中添加了AspNetUser类。基于这个类,将它作为模型传递给view是好的,还是仍然建议使用register模型?我的意思是,如果我在我的httpPost方法中使用AspNetUser,或者我应该坚持使用基于视图的注册模型,这可能也是个好主意吗?我还没有完全理解。你应该一直使用视图模型。控制器操作将视图模型传递到视图或从视图获取视图模型。从我所看到的这个AspNetUser类是一些只应该由服务层使用的域模型。对于特定的寄存器视图,它有无数无用的东西。
    @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>