在与Validation和ModelState.IsValid一起使用EditorForModel字段时,如何返回到原始视图,但保留填充的字段?
调试时,我可以看到传递回视图的模型中包含字段数据,但是文本输入等不包含值。
我在做什么错了?
控制器代码如下:
[Authorize]
public ActionResult ChangePassword()
{
return View(new Views.PublicAuthChangePassword());
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("ChangePassword")]
public ActionResult ChangePassword_Post(ChangePasswordVM vm)
{
try
{
if (ModelState.IsValid)
{
MyUser user = new MyUser();
bool changeResponse = MyUser.ChangePassword(vm.OldPassword, vm.NewPassword);
if (changeResponse)
ViewBag.Message = "Password changed successfully";
else
ViewBag.Message = "Unable to change password";
}
}
catch (System.ArgumentNullException ex)
{
//Either old password or new password are null
}
catch (System.ArgumentException ex)
{
//Either old password or new password are empty string
}
catch (PlatformNotSupportedException ex)
{
//This method is not available.
}
catch (Exception ex)
{
//An unknown error occurred
}
return View(vm);
}
查看:
@model ChangePasswordVM
@using (Html.BeginForm("ChangePassword", "MyController", FormMethod.Post, new { @class = "change-password" }))
{
<h2>Change My Password</h2>
@Html.AntiForgeryToken()
@Html.EditorForModel(Model)
<input id="btnChangePassword" type="submit" value="Change password" />
}
型号:
public class ChangePasswordVM
{
[Required(ErrorMessage = "Old password is required")]
[DataType(DataType.Password)]
public string OldPassword { get; set; }
[Required(ErrorMessage = "New password is required")]
[DataType(DataType.Password)]
public string NewPassword { get; set; }
[Required(ErrorMessage = "Confirm password is required")]
[DataType(DataType.Password)]
[CompareAttribute("NewPassword", ErrorMessage = "Password doesn't match.")]
public string ConfirmPassword { get; set; }
}
谢谢 西蒙
答案 0 :(得分:0)
我会翻转您的模型状态检查。
public ActionResult ChangePassword_Post(PasswordViewModel vm)
{
if (!ModelState.IsValid)
{
return View(vm);
}
try
{
MyUser user = new MyUser();
bool changeResponse = MyUser.ChangePassword(vm.OldPassword, vm.NewPassword);
if (changeResponse)
ViewBag.Message = "Password changed successfully";
else
ViewBag.Message = "Unable to change password";
}
catch (System.ArgumentNullException ex)
{
//Either old password or new password are null
}
catch (System.ArgumentException ex)
{
//Either old password or new password are empty string
}
catch (PlatformNotSupportedException ex)
{
//This method is not available.
}
catch (Exception ex)
{
//An unknown error occurred
}
ViewBag.Message = "Unable to change password";
return View(vm);
}
如果模型状态检查失败,这会将模型验证错误返回到视图。还将使用您的viewmodel值重新填充所有字段。
如果有任何下拉列表,则需要明确地重新创建数据并将其传回。
您还必须在末尾再次设置ViewBag.Message,因为只有在调用失败而没有引发异常的情况下才设置它。
您还应该遵循PRG模式并重定向到显示页面或索引页面,而不是同一视图。