2017-10-11 104 views
1

我正在使用EntityFramework和.NET Core中的MVC,並且遇到了一個我不確定如何處理的問題。我有一個帶有Password字段的用戶模型。我希望編輯用戶模型,但我不希望Password字段與其餘用戶字段出現在同一編輯視圖中。隱藏密碼很簡單,但現在模型在保存編輯時總是無法驗證。排除模型的密碼字段,導致模型驗證失敗

我已經玩弄了只隱藏密碼字段在視圖中工作,但離開密碼顯示在頁面源。我也嘗試創建一個UserEditView模型,但是它創建了很多翻譯代碼,這些代碼對於我想要實現的內容而言不應該是必需的。

任何幫助將不勝感激。以下是我一直在使用的代碼。

型號: User.cs

public class User 
{ 
    [Display(Name="User ID")] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int ID { get; set; } 

    [Required()] 
    [Display(Name="Email Address")] 
    [DataType(DataType.EmailAddress)] 
    public string Email { get; set; } 

    [Required()] 
    public string Name { get; set; } 

    [Required] 
    [DataType(DataType.Password)] 
    public string Password { get; set; } 

    [Required()] 
    public string Salt { get; set; } 
} 

編輯動作: UsersController.cs

public async Task<IActionResult> Edit(int? id) 
{ 
    if (id == null) 
    { 
     return NotFound(); 
    } 

    var employee = await _context.Employees.SingleOrDefaultAsync(m => m.ID == id); 
    if (employee == null) 
    { 
     return NotFound(); 
    } 
    ViewData["LocationID"] = new SelectList(_context.Locations, "ID", "Address", employee.LocationID); 
    ViewData["PositionID"] = new SelectList(_context.Jobs, "ID", "Name", employee.PositionID); 

    return View(employee); 
} 


[HttpPost] 
[ValidateAntiForgeryToken] 
public async Task<IActionResult> Edit(int id, [Bind("ID,Email,Name,LocationID,PositionID")] Employee employee) 
{ 
    if (id != employee.ID) 
    { 
     return NotFound(); 
    } 

    if (ModelState.IsValid) 
    { 
     try 
     { 
      _context.Update(employee); 
      await _context.SaveChangesAsync(); 
     } 
     catch (DbUpdateConcurrencyException) 
     { 
      if (!EmployeeExists(employee.ID)) 
      { 
       return NotFound(); 
      } 
      else 
      { 
       throw; 
      } 
     } 
     return RedirectToAction(nameof(Index)); 
    } 
    ViewData["LocationID"] = new SelectList(_context.Locations, "ID", "Address", employee.LocationID); 
    ViewData["PositionID"] = new SelectList(_context.Jobs, "ID", "Name", employee.PositionID); 
    return View(employee); 
} 
+2

更改您的模型,使其沒有該屬性。爲特定視圖設計模型並沒有什麼錯,事實上這就是MVC的一個重點。 – Crowcoder

+0

你可以從發送的ID中查找密碼,設置employee.password = [查找密碼],然後保存?我不會將密碼暴露給視圖,但在控制器中不應該有任何問題。 – Aaron

+0

@Crowcoder這是我嘗試過的事情之一,但是當我嘗試時使用Entity Framework和Scaffolded控制器時,我總是收到'UserEditViewModel'表不存在的錯誤。 – TheDude

回答

0

在你的控制器,你可以做到以下幾點:

ModelState.Remove("Password"); 

這將防止該字段被驗證。

但是,這不是一個很乾淨的修復程序。如果您在當前視圖中未使用該字段,則應考慮將該字段移至其他模型。

+0

從ModelState中刪除密鑰並不能解決驗證錯誤,但Customer ViewModel絕對是最好的方法,所以這就是我現在正在做。 – TheDude