Reputation: 11607
I have a settings page on my site that uses these model classes:
public class NameVm
{
public string GivenName { get; set; }
public string FamilyName { get; set; }
}
public class PasswordVm
{
public string OldPassword { get; set; }
public string NewPassword { get; set; }
public string ConfirmPassword { get; set; }
}
public class AccountVm
{
public NameVm Name { get; set; }
public PasswordVm Password { get; set; }
}
This is the controller:
public class AccountController : Controller
{
[HttpGet]
public override ActionResult Index()
{
var accountVm = AccountVmFromActiveUser();
return View(accountVm);
}
[HttpPost]
public ActionResult EditName(NameVm vm)
{
...
}
[HttpPost]
public ActionResult EditPassword(PasswordVm vm)
{
if (ModelState.IsValid)
{
if (!ValidateUser(this.ActiveUser, vm.OldPassword))
{
ModelState.AddModelError("????",
"Existing password is incorrect.");
}
else
UpdateUserPassword(vm);
}
var accountVm = AccountVmFromActiveUser();
accountVm.Password = vm;
return View(accountVm);
}
}
In my Account.cshtml
file I define two forms - one that submits to EditName
, one that submits to EditPassword
. It's a big file, so here is a small excerpt:
@Html.EditorFor(model => model.Password.OldPassword)
@Html.ValidationFor(model => model.Password.OldPassword)
My question is: How do I get ValidationFor
to display the error message I add in the EditPassword
method? I tried using a key of "Password.OldPassword"
, but this didn't work.
Alternatively, am I taking the wrong approach here? How should I handle having two forms on the same page?
Upvotes: 0
Views: 664
Reputation: 971
You can use Partial Views.
1) in Account.cshtml
separate the form that submits passord and put it in a partial view _EditPassword.cshml
(usually I put the partial views in Views\Shared
folder)
use
@Html.Partial("_EditPassword", @Model.Password)
to render the partial View in Account.cshtml
2) in the partial view _EditPassword.cshtml
you can use
@Html.EditorFor(model => model.OldPassword)
@Html.ValidationFor(model => model.OldPassword)
and you should see validation errors
Upvotes: 1