根据这篇文章
第二个答案,我尝试为我的注册页面创建一个下拉列表。注册页面有一个字段,您可以PossibleAccessRight
在注册用户时为他/她选择该字段,该字段应保存在AccessRight
属性中。
现在我什至无法在下拉列表中显示项目
我的模型看起来像这样
public class UserModel
{
public int UserId { get; set; }
[Required]
[EmailAddress]
[StringLength(100)]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email ID ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(20,MinimumLength = 6)]
[Display(Name = "Password ")]
public string Password { get; set; }
[Required]
[Display(Name = "First Name ")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name ")]
public string LastName { get; set; }
[Required]
[Display(Name = "Address ")]
public string Address { get; set; }
public List<string> PossibleRights;
[Required]
[Display(Name = "Access Rights")]
public string AccessRight { get; set; }
public UserModel()
{
PossibleRights = new List<string>()
{
{"High"},
{"Low"},
};
}
}
在控制器中,我在注册方法中有这个,即 httppost 方法
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(Models.UserModel user)
{
var rights = new UserModel();
if (ModelState.IsValid)
{
using (var db = new DBaseEntities())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var sysUser = db.SystemUsers.Create();
sysUser.FirstName = user.FirstName;
sysUser.Email = user.Email;
sysUser.Password = encrpPass;
sysUser.PasswordSalt = crypto.Salt;
db.SystemUsers.Add(sysUser);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("","Login data is incorrect.");
}
return View(rights);
}
此方法的视图如下所示
<div class="editor-label">@Html.LabelFor(u=> u.FirstName)</div>
<div class="editor-field"> @Html.TextBoxFor(u=> u.FirstName)</div>
<br/>
<div class="editor-label">@Html.LabelFor(u=> u.LastName)</div>
<div class="editor-field"> @Html.TextBoxFor(u=> u.LastName)</div>
<br/>
<div class="editor-label">@Html.LabelFor(u=> u.Address)</div>
<div class="editor-field"> @Html.TextBoxFor(u=> u.Address)</div>
<br/>
<div class="editor-label">@Html.LabelFor(u=> u.Email)</div>
<div class="editor-field"> @Html.TextBoxFor(u=> u.Email)</div>
<br/>
<div class="editor-label">@Html.LabelFor(u=> u.Password)</div>
<div class="editor-field"> @Html.PasswordFor(u=> u.Password)</div>
<br/>
<div class="editor-label">@Html.LabelFor(u=> u.AccessRight)</div>
<div class="editor-field"> @Html.DropDownListFor(u=> u.PossibleRights, new SelectList(Model.PossibleRights))</div>//error at this line(NullReference exception)
<br/>
<input type="submit" value="Register"/>
知道我做错了什么吗?另外,我在下拉列表中显示项目的方法好吗?如果有的话,你能提出更好的主意吗?