我對剃鬚刀和mvc控制器的使用經驗很少。我想在我的註冊視圖中添加一個下拉框。我在網上嘗試了一些不同的東西,但我不知道如何通過應用程序用戶訪問我需要的類。我想添加一個公司列表。通過賬戶視圖模型我真的迷失了方向。我刪除了公司類的關係,因爲我必須清理它。不知道這需要什麼。一個用戶只能有一個公司。如何使用選擇框來擴展身份用戶屬性
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
公司類
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public List<Document> Documents { get; set; }
}
帳戶查看模型
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 = "UserName")]
public string UserName { get; set; }
[Required]
[Display(Name = "CompanyName")]
public int CompanyId { get; set; }
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
//Property for the options
public IEnumerable<SelectListItem> CompanyOptions(string selected)
{
//This is just static - get it from somewhere else (database?)
return new List<SelectListItem>{
new SelectListItem{ Text = "Company 1", Value = "1", Selected = selected.Equals("1") },
new SelectListItem{ Text = "Company 2", Value = "2", Selected = selected.Equals("2") }
};
}
}
查看
<div class="form-group">
@Html.LabelFor(model => model.CompanyId, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownFor(m => m.CompanyId, Model.CompanyOptions(Model.CompanyId), null)
</div>
錯誤消息
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'DropDownFor' and no extension method 'DropDownFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?) Source Error: Line 41: @Html.LabelFor(model => model.CompanyId, new { @class = "control-label col-md-2" }) Line 42: Line 43: @Html.DropDownFor(m => m.CompanyId, Model.CompanyOptions(Model.CompanyId), null) Line 44: Line 45: Blockquote
新的錯誤
Compiler Error Message: CS0121: The call is ambiguous between the following methods or properties: 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable, System.Collections.Generic.IDictionary)' and 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable, string)'
UserAdmin控制器
// GET: /Users/Create
public async Task<ActionResult> Create()
{
//Get the list of Roles
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
return View();
}
// POST: /Users/Create
[HttpPost]
public async Task<ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = userViewModel.UserName,
Email = userViewModel.Email,
CompanyId = userViewModel.CompanyId,
Name = userViewModel.Name
};
user.UserName = userViewModel.UserName;
user.Email = userViewModel.Email;
user.CompanyId = userViewModel.CompanyId;
user.Name = userViewModel.Name;
// Then create:
var adminresult = await UserManager.CreateAsync(user, userViewModel.Password);
//Add User to the selected Roles
if (adminresult.Succeeded)
{
if (selectedRoles != null)
{
var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
return View();
}
}
}
else
{
ModelState.AddModelError("", adminresult.Errors.First());
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
return View();
}
return RedirectToAction("Index");
}
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
return View();
}
賬戶控制器
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, CompanyId = model.CompanyId, Name = model.Name };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var 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 this link: <a href=\""
+ callbackUrl + "\">link</a>");
ViewBag.Link = callbackUrl;
return View("DisplayEmail");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
註冊視圖模型
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 = "UserName")]
public string UserName { get; set; }
[Required]
[Display(Name = "CompanyName")]
public int CompanyId { get; set; }
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
//Property for the options
public IEnumerable<SelectListItem> CompanyOptions(int selected)
{
//This is just static - get it from somewhere else (database?)
return new List<SelectListItem>{
new SelectListItem{ Text = "Company 1", Value = "1", Selected = selected.Equals("1") },
new SelectListItem{ Text = "Company 2", Value = "2", Selected = selected.Equals("2") }
};
}
}
好看起來不錯。我確實需要一些幫助。我正在使用包含用戶角色和UserAdmin控件的種子項目。所以還有一些我習慣的控制器。你能幫助放置你的代碼嗎?我更新了我的帖子 – texas697 2015-02-12 18:35:21
我不明白你的評論。你有什麼問題?你的'Create()'方法看起來很奇怪 - 除了設置'user'的值兩次,'params string [] selectedRoles'是什麼?爲什麼'selectedRoles'不是視圖模型的屬性,你如何渲染'selectedRoles'的控件?你編輯只是重複(我認爲)原來的'RegisterViewModel',所以我有點困惑。在任何情況下,它似乎並不涉及你原來的問題或你得到的錯誤,所以它應該是一個新問題 – 2015-02-12 22:17:43
這就是問題,這是一個種子項目,我用它,因爲它有userroles和用戶管理就緒去。我真的不知道它是如何設置的。我只習慣擁有一個賬戶控制器,它有一個賬戶控制器和一個userAdmin控制器。所以當我試圖插入你的東西時,我有點迷茫。稍後我會再次處理它。我仍然計劃給你信貸給你的幫助。謝謝 – texas697 2015-02-13 00:25:01