使用模型MVC中的Html.EditorForModel用数据填充表单字段



在验证和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; }
}

谢谢Simon

我会翻转您的模型状态检查。

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);
}

如果模型状态检查失败,这会将模型验证错误返回到视图中。它还将使用您的视图模型值重新填充任何字段。

如果有任何下拉列表,则需要显式地重新创建数据并将其传递回。

您还必须在结束时再次设置ViewBag.Message,因为只有在调用失败且未引发异常时才进行设置。

您还应该遵循PRG模式和重定向到显示或索引页面,而不是相同的视图。

最新更新