2016-04-27 16 views
0

情況是,我有一個複雜的模型,有大量的數據可供查看,除此之外,還有控制面板,例如更改密碼。查看多種型號並只發佈一個

將提交另一個屬性模型的一個大型模型。
大模型內的信息需要加載並在POSTing

不是必需的模式

public class ProfileModel { 
    // This is the submitted model: 
    public PasswordChangeModel Password = new PasswordChangeModel(); 

    // Personal Info 
    public string Name {get; set;} 
    public string LastName {get; set;} 
    // 15~ more fields 
} 

密碼模型W /驗證

public class PasswordChangeModel { 
    [Required] 
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
    [DataType(DataType.Password)] 
    [Display(Name = "OldPassword")] 
    public string OldPassword { 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 = "Repeat password")] 
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
    public string RepeatPassword { get; set; } 
} 

控制器Catching-動作

[HttpPost] 
[ValidateAntiForgeryToken] 
public IActionResult ChangePassword(PasswordChangeModel model) { 
    if (!ModelState.IsValid) //validate the model 
     return View(model); 

    //do stuff ... 
    return Index(); 
} 

的HTML生成表單

<form asp-controller="Profile" asp-action="ChangePassword" asp-antiforgery="true"> 
    <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>   
    <label asp-for="Password.OldPassword">Old Password</label> 
    <input asp-for="Password.OldPassword"/> 
    <label asp-for="Password.Password">New Password</label> 
    <input asp-for="Password.Password"/> 
    <label asp-for="Password.RepeatPassword">New Password Repeat</label> 
    <input asp-for="Password.RepeatPassword"/> 
    <input type="submit" class="btn" name="submit" value="Change"/> 
</form> 

現在的問題

檢查代碼後,我的問題是 - 是否有可能提出這樣的說法,如果不是最簡單最乾淨的方法。

注意:我總是可以在密碼更改的模型ProfileModel中包含3個字段,但A-It很醜,B-It仍然會加載整個ProfileModel數據。

+0

是否有理由不能使用局部視圖?您仍然可以將PasswordChangeModel作爲主視圖的一部分,但是您可以將它分離出來,以便在一個視圖中不使用兩個模型。 – Marqueone

回答

0

這就是我最終做的。 工作得很好。

[HttpPost] 
[ValidateAntiForgeryToken] 
public IActionResult ChangePassword([Bind(Prefix = "Password.OldPassword")]string Password_OldPassword, 
    [Bind(Prefix = "Password.Password")] string Password_Password, 
    [Bind(Prefix = "Password.RepeatPassword")] string Password_RepeatPassword) { 
    //Change the password 
} 

BIND屬性重定向的Password.OldPassword值來Password_OldPassword

0

我會說最乾淨的方法是做一個單獨的更新密碼視圖。這或切換到ajax文章,以便您可以發佈而無需重新加載頁面。如果你不能建立一個模型,可以做一個往返服務器沒有重新填充它,那麼不要做標準的表單發佈。它可以完成,但是當我看到它時,通常在驗證錯誤時重新渲染頁面時會出現細微的錯誤。 在腳下拍攝自己很容易。