generate dropdownlist from a table in database

2019-05-31 00:28发布

问题:

I'm tryng to be more precise to my previous question which can be found here, I got some nice answers but couldn't figure out how to use it in my situation Previous question I got some nice answers but couldn't figure out how to use it in my situation.

basically I want to have registration page which contains

  1. Email //Comes from my AspNetUser(datamodel) class, also AspNetUsers table exists in database.
  2. UserName//Comes from my AspNetUser(datamodel) class, also AspNetUsers table exists in database.
  3. Password//Comes from my AspNetUser(datamodel) class, also AspNetUsers table exists in database.
  4. Role//dropdownlist, comes from Role(datamodel) class, also Roles table exists in database

In my controller I have impelmented my Register method in following way:

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

in my get method i'm passing the roles to view and right now i'm using AspNetUser as model in 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>

can u tell me how to get that dropdownlist and how can I pass that selected value to controller to use it so that i can put user in role during registration? Would it be better to create new model for Registration?

Edit: AspNetUser model

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

    }

回答1:

You'd better have a view model specifically designed for this view. Think of what information you need in the view and define your view model:

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

As you can see from this view model, in order to have a dropdown list you need 2 properties: one scalar property that will hold the selected value and one collection property to hold the list of available values.

and then:

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

and finally the corresponding view:

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