【发布时间】:2016-05-19 18:06:59
【问题描述】:
情况是我有一个复杂的模型,需要查看大量数据,除此之外还有控制面板,例如密码更改。
一个大模型和另一个属性模型将被提交。
大模型内的信息需要加载,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
}
带验证的密码模型
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; }
}
控制器捕捉动作
[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-它很难看,B-它仍然会加载整个 ProfileModel 数据。
【问题讨论】:
-
是否有理由不能为此使用局部视图?您可能仍将 PasswordChangeModel 作为主视图的一部分,但您可以在地图集上将其分离得更多,这样您就不会在一个视图中使用两个模型。
标签: c# asp.net-core-mvc