I have a scenario like i need to display error message which is coming from DB on Edit [GET] request.
I know this can be done if request type is of [POST], but how can we do this in [GET] request.
Same Code:
[HttpGet]
public ActionResult Edit(Int64 ID)
{
tblSample1 model = GetData(ID);
ViewData.ModelState.AddModelError(model.Username, "Invalid Username provided.");
return View("~/Views/Sample1/_Edit.cshtml", model);
}
[HttpPost]
public ActionResult Edit(tblSample1 model)
{
if (ModelState.IsValid)
{
......
......
}
}
This should still work. The first argument to AddModelError
is the key. You're passing it the value of the property Username
.. which won't work. What you want is to pass the property name as the key:
ModelState.AddModelError("Username", "Invalid Username provided.");
// ^^^^^^^^^^ Username property of model
Of course this must be coupled with a ValidationSummary
or ValidationMessage
in your view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With