【发布时间】:2018-09-11 02:49:34
【问题描述】:
“/”应用程序中的服务器错误。 具有“UserType”键的 ViewData 项属于“System.String”类型,但必须属于“IEnumerable”类型。
class view
<div class="form-group">
@Html.LabelFor(m => m.UserType, new { @class = "col-md-2 control-label" })
<div class="col-md-2">
@Html.DropDownList("UserType", ViewBag.UserTypelist as SelectList, new { @class = "form-control" })
</div>
</div>
class model
public class RegisterViewModel
{
[Required]
[DisplayName("نوع الحساب")]
public string UserTypelist { get; set; }
}
class controller
[AllowAnonymous]
public ActionResult Register()
{
//to show drop down list
ViewBag.UserTypelist = new SelectList(db.Roles, "Name", "Name");
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
ViewBag.UserTypelist = new SelectList(db.Roles,"Name", "Name");
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, UserType= model.UserTypelist };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
await UserManager.AddToRoleAsync(user.Id,model.UserTypelist);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
如何解决这个问题,请任何帮助我解决这个问题的人
【问题讨论】:
-
您的屏幕截图显示您正在将
ViewBag.UserType投射到SelectList。您以文本形式发布的代码使用ViewBag.UserTypelist代替。显然你两者都有,但没有使用正确的,你发布的代码实际上不是你正在运行的代码。 -
你好 -GSerg 我编辑了我的图片描述 请再次查看图片描述和当前图片描述显示下面代码的状态
-
您可能希望创建某种类型的 UserTypeList 和 IEnumerable。也许 IEnumerable
. -
在返回视图之前,您没有在 POST 方法中分配
ViewBag.UserTypelist的值(您分配它的唯一位置是当ModelState有效时这是没有意义的,因为您随后会重定向跨度> -
而您的
public string UserTypelist { get; set; }属性毫无意义 - 我假设您的意思是public string UserType { get; set; }因为这是您要绑定的属性。
标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-3