This blog
explain how to show validation error in MVC View from Controller.
There is
different ways to pass error message from controller to View
·
ModelState
·
ViewBag
Use AddModelError() method of
ModelState to display error message :
Model State
is a Key/Value dictionary,
which is used to store state of Model, which is posed from Action and it
includes validation information for each fields.
It expose the
main properties/method, with help of this, you can validate the posted model by
calling IsValid Property, if Model
has any failed validation, it return false otherwise true .
if
(ModelState.IsValid)
{
// Call further API/Service or business object
}
else
{
// Show error message
}
You can add
validation error message by using AddModelError() method and you can use @Html.ValidationSummary() to display the validation message on
view, basically the ValidationSummary
helper method generates an unordered list (ul element) of validation messages
that are in the ModelStateDictionary object and it can be used to display all
the error messages for all the fields. It can also be used to display custom
error messages
[HttpPost]
public
ActionResult SavePerson(Person model)
{
string Name = model.Name;
int firstOccurance = Name.IndexOf(',');
int lastOcuurance = Name.LastIndexOf(',');
if (firstOccurance == 0)
{
ModelState.AddModelError("Name", "Name should not begin with
Comma ','.");
}
else if (lastOcuurance == Name.Length - 1)
{
ModelState.AddModelError("Name", "Name should not end with Comma ','.");
}
return View("Person", person);
}
HTML Razor
View:
@model Person
@Html.ValidationSummary()
<div>
<div class="row">
<div class="col-sm-12">
@Html.Partial("_Person", Model })
</div>
</div>
</div>
HTML View:
Use Viewbag to display Error Message:
ViewBag is
used to send data from controller to view and to display the error message, we
can also use the ViewBag to transfer error or validation message from
controller to view.
MVC Controller:
[HttpPost]
public IActionResult SavePerson(Person
person)
{
string Name = person.Name;
int firstOccurance = Name.IndexOf(',');
int lastOcuurance = Name.LastIndexOf(',');
if (firstOccurance == 0)
{
ViewBag.ErrorMessage = "Name should not
begin with Comma ','.";
// ModelState.AddModelError("Person.Name", "Name
should not begin with Comma ','.");
}
else if (lastOcuurance == Name.Length - 1)
{
ViewBag.ErrorMessage = "Name should not
begin with Comma ','.";
//ModelState.AddModelError("Person.Name", "Name
should not end with Comma ','.");
}
return View("Person", person);
}
HTML Razor
View:
<div class="alert alert-danger">
<p>@ViewBag.ErrorMessage</p>
</div>
No comments:
Post a Comment