【发布时间】:2014-10-10 11:05:07
【问题描述】:
我正在使用 ASP.NET mvc 4 模板来创建我的应用程序。
我在 UserProfile 字段中创建了一个 UserType 作为字符串,并进行了迁移以更新数据库。没错。
我的问题是,当我在注册视图中注册一个新用户时,应用程序保存所有字段,但 UserType,它保存 null,我该如何解决?我读了一些有类似问题的主题,但我不知道对我有什么用。我的代码如下:
在@StephenMuecke的帮助下,我在这里发布更新的代码,问题还没有解决:
//Models
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string UserType { get; set; } //flag de tipo usuário musico ou ouvinte
}
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; }
[Required]
[Display(Name = "Tipo de Usuario")]
public string UserType { get; set; }
}
//Controller
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
var user = new UserProfile() { UserName = model.UserName, UserType = model.UserType };
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
//View
@model TestTcc2.Models.RegisterModel
<div class="form-group">
<label for="icode" class="col-md-3 control-label">Tipo de usuário</label>
<div class="col-md-9">
@*Html.DropDownListFor(m=> m.UserType, userTypes)*@
@Html.RadioButtonFor(m => m.UserType, "Ouvinte", new { id = "Ouvinte" })
@Html.Label("Ouvinte")
@Html.RadioButtonFor(m=>m.UserType, "Musico", new { id= "Musico" })
@Html.Label("Musico")
</div>
</div>
编辑:
要解决单选按钮的问题,我需要更新调用 UserProfile 类的 Post Register 方法。
这是代码:http://pastebin.com/Mwd4QD6U
现在我正在创建一个新主题来询问我在注册期间遇到的异常错误 话题链接:MemberShipException during the User Register at ASP.NET
【问题讨论】:
-
UserType"Ouvinte" 和 "Musico" 的可能值是多少? -
RadioButtonFor 中定义的值是:Ouvinte 和 Musico。 @StephenMuecke
标签: c# asp.net-mvc asp.net-mvc-4 radio-button html.dropdownlistfor