从数据库中的表生成下拉列表 [英] generate dropdownlist from a table in database
问题描述
我正在尝试更精确地回答我先前的问题,可以在这里找到,我得到了一些不错的答案,但无法弄清楚如何在我的情况下使用它
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
-
Email
//来自我的AspNetUser(datamodel)类,数据库中也存在AspNetUsers表. -
UserName
//来自我的AspNetUser(datamodel)类,数据库中也存在AspNetUsers表. -
Password
//来自我的AspNetUser(datamodel)类,数据库中也存在AspNetUsers表. -
Role
//下拉列表,来自Role(datamodel)类,数据库中也存在Roles表
Email
//Comes from my AspNetUser(datamodel) class, also AspNetUsers table exists in database.UserName
//Comes from my AspNetUser(datamodel) class, also AspNetUsers table exists in database.Password
//Comes from my AspNetUser(datamodel) class, also AspNetUsers table exists in database.Role
//dropdownlist, comes from Role(datamodel) class, also Roles table exists in database
在我的控制器中,我通过以下方式实现了我的Register
方法:
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();
}
}
在我的get方法中,我将roles
传递给视图,现在我在视图中使用AspNetUser
作为模型
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>
您能告诉我如何获取该dropdownlist
以及如何将所选值传递给控制器以使用它,以便我可以在注册过程中让用户扮演角色吗?创建新的注册模型会更好吗?
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?
AspNetUser模型
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; }
}
}
推荐答案
您最好具有专门为此视图设计的视图模型.考虑一下视图中需要哪些信息并定义视图模型:
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; }
}
从该视图模型可以看到,要拥有一个下拉列表,您需要2个属性:一个将保存所选值的标量属性和一个用于保存可用值列表的collection属性.
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.
然后:
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>
这篇关于从数据库中的表生成下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!