2015-02-10 62 views
3

我對剃鬚刀和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") } 
     }; 
    } 
} 

回答

2

第二個錯誤消息是對DropDownListFor()的第三個參數使用null的結果。電話是模糊的,因爲是接受string labelOption接受object htmlAttributes

取出第三個參數(或者,如果你想要一個選項標籤,使之成爲string,例如string.Empty,或者"-Please select-"

過載和一個您也不應設置SelectListItemSelected財產。 @Html.DropDownListFor(m => m.CompanyId, ...對屬性CompanyId有約束力,所以如果CompanyId的值與其中一個選項的值相匹配,那麼將選擇該選項(在上面的代碼中,如果CompanyId=2,則將選擇第二個選項)。Selected屬性的值將被忽略。相反,改變CompanyOptions一個屬性

public IEnumerable<SelectListItem> CompanyOptions { get; set; } 

,並在控制器

public ActionResult Create() 
{ 
    RegisterViewModel model = new RegisterViewModel(); 
    model.CompanyId = 2; // set this if you want to display a specific company 
    ConfigureViewModel(model); 
    return View(model); 
} 

public ActionResult Create(RegisterViewModel model) 
{ 
    if(!ModelState.IsValid) 
    { 
    ConfigureViewModel(model); 
    return View(model); 
    } 
    // Save and redirect 
} 

private void ConfigureViewModel(RegisterViewModel model) 
{ 
    model.CompanyOptions = new List<SelectListItem>() 
    { 
    new SelectListItem() { Text = "Company 1", Value = "1" }, 
    new SelectListItem() { Text = "Company 2", Value = "2" } 
    }; 
} 

如果您的訪問從一個數據庫,它更可能是企業要

model.CompanyOptions = new SelectList(db.Companies, "ID", "Name") 
+0

好看起來不錯。我確實需要一些幫助。我正在使用包含用戶角色和UserAdmin控件的種子項目。所以還有一些我習慣的控制器。你能幫助放置你的代碼嗎?我更新了我的帖子 – texas697 2015-02-12 18:35:21

+0

我不明白你的評論。你有什麼問題?你的'Create()'方法看起來很奇怪 - 除了設置'user'的值兩次,'params string [] selectedRoles'是什麼?爲什麼'selectedRoles'不是視圖模型的屬性,你如何渲染'selectedRoles'的控件?你編輯只是重複(我認爲)原來的'RegisterViewModel',所以我有點困惑。在任何情況下,它似乎並不涉及你原來的問題或你得到的錯誤,所以它應該是一個新問題 – 2015-02-12 22:17:43

+0

這就是問題,這是一個種子項目,我用它,因爲它有userroles和用戶管理就緒去。我真的不知道它是如何設置的。我只習慣擁有一個賬戶控制器,它有一個賬戶控制器和一個userAdmin控制器。所以當我試圖插入你的東西時,我有點迷茫。稍後我會再次處理它。我仍然計劃給你信貸給你的幫助。謝謝 – texas697 2015-02-13 00:25:01

0

您需要將公司列表添加到您的註冊模型中,在視圖中將其呈現給用戶,然後將所選值應用到您的發佈操作中。

型號:

//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.DropDownListFor(m => m.CompanyId, Model.CompanyOptions(Model.CompanyId), null) 
    </div> 
</div> 

現在你可以在Register行動使用模型上的CompanyId財產。

+0

我更新我的職務。需要一些幫助。謝謝 – texas697 2015-02-10 12:12:35

+0

我的不好 - 見更新。應該是'DropDownListFor'。 – 2015-02-10 12:19:33

+0

不用擔心,但現在得到這個'TransparentEnergy.Models.RegisterViewModel.CompanyOptions(string)'的最佳重載方法匹配有一些無效參數 – texas697 2015-02-10 12:26:50

相關問題