我正在使用ASP.NET Web应用程序模板,并尝试允许用户在注册时选择一个角色。
这是我目前得到的。
是吗
查看
<fieldset class="col-lg-5 .col-md-5">
<legend>Registration Form</legend>
<p>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
</p>
<p>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
</p>
<p>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
</p>
<p>
@Html.DropDownListFor(model => model.Type, Model.TypeList)
</p>
<input type="submit" value="Register" class="btn btn-default" />
</fieldset>
模型
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string Type { get; set; }
public IEnumerable<SelectListItem> TypeList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "athlete", Value = "athlete"},
new SelectListItem { Text = "coach", Value = "coach"},
};
}
}
}
控制器
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
Roles.AddUserToRole(model.UserName, model.Type);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
我觉得我很接近,但我不能安静地得到它,我收到了这个错误
编译器错误消息:Models.RegisterModel&gt;'不包含'DropDownListFor'的定义和最佳扩展方法重载'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,System.Linq.Expressions.Expression&gt;,System.Collections.Generic .IEnumerable)'有一些无效的参数
答案 0 :(得分:0)
您是否在HttpGet Register方法中初始化了模型?如下......
[AllowAnonymous]
public ActionResult Register()
{
var model = new RegisterModel();
return View(model);
}
我创建了一个空模板MVC4 app,添加了你的代码,得到了对象引用没有设置错误作为默认寄存器模型没有传递模型对象来查看你试图访问的内容(即在DropDownListFor()中加载TypeInt)。
然后我在Get方法中初始化了模型,如上所示。一切正常,我能够在注册视图中选择一个角色。
检查这是否有帮助。
答案 1 :(得分:0)
看一下你应该删除的最后一个逗号:
new SelectListItem { Text = "athlete", Value = "athlete"},
new SelectListItem { Text = "coach", Value = "coach"}