我在綁定兩個單選按鈕到我在模型中指定的角色的enum
方面存在問題。該角色是在註冊時選擇的,當我設置角色並提交表單時,即使我單擊Receiver
角色的其他單選按鈕,也只有Provider
的第一個角色被傳遞給控制器。MVC5單選按鈕組和角色
我已經調試並設置了大部分代碼的斷點,但我只看到Provider
被髮送到控制器的角色。 問題:如何正確地將我的枚舉綁定到我的單選按鈕?還是有我應該使用的另一種方法?
注意:註冊模型的其餘部分正確綁定,其他所有內容都提交併正確插入數據庫,但角色除外。
MODEL
public enum AppRoles
{
Provider,
Receiver,
Admin
}
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { 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 = "Role")]
public AppRoles Role { get; set; }
}
VIEW(僅適用於單選按鈕相關的代碼)
<div class="form-group">
<div class="col-md-12 text-center">
<h3>Select Your Account Type</h3>
<div class="btn-toolbar" data-toggle="buttons">
<label class="btn btn-primary">
Service Receiver
@Html.RadioButtonFor(m => m.Role, AppRoles.Receiver, "Receiver")
</label>
<label class="btn btn-primary">
Service Provider
@Html.RadioButtonFor(m => m.Role, AppRoles.Provider, "Provider")
</label>
</div>
</div>
控制器
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
result = UserManager.AddToRole(user.Id, model.Role.ToString());
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
if (model.Role.ToString() == "Provider")
{
return RedirectToAction("ProviderPostRegistration", "Account");
}
else if (model.Role.ToString() == "Receiver")
{
return RedirectToAction("ReceiverPostRegistration", "Account");
}
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
「@ Html.RadioButtonFor()」的第三個參數沒有意義(它用於添加html屬性) –
您是否有任何其他屬性Role的控件(可能是這些視圖中屬性的隱藏輸入單選按鈕)? –
我刪除了第三個參數,但無濟於事。我發現這個方法還有兩個重載,他們會派上用場嗎?而且視圖中的其他任何內容都不是簡單的電子郵件,密碼和確認密碼字段。 –