To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.
You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element. You have to define validations inside the class as per requirement.
The error typically means that your Model doesn't meet the requirements to be validated. In your example, your FirstName , LastName , Email , Subject and Message properties are decorated with the [Required] attribute. This means that those values shouldn't be null and empty otherwise your condition if(ModelState.
IsValid is false now. That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.
I have an action that saves a record by calling my BLL entity's Save method. The entity takes care of its own internal validation and if a field is required but fails validation because a user didn't enter a value then the entity throws up an error. I'm catching that error in my action and returning the same view. The problem is the error isn't showing in my ValidationSummary.
Yes I realize I have view model validation by attibute with MVC but this entity is used elsewhere and must have redundant validation if the UI doesn't/can't do it, such as used in a batch service job.
Here is my action:
public ActionResult Edit(EntityModel model) {
if (ModelState.IsValid) {
var entity = new Entity(model.ID, model.Name, model.IsActive);
try {
entity.Save(User.Identity.Name);
return RedirectToAction("List");
}
catch (Exception ex) {
ModelState.AddModelError("", ex.Message);
}
}
return View(model);
}
Here is my View:
@model ELM.Select.Web.Models.EntityModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>DefermentTypeViewModel</legend>
@Html.HiddenFor(model => model.ID)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.IsActive)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.IsActive)
@Html.ValidationMessageFor(model => model.IsActive)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Why wouldn't the error I add to modelstate be shown in my validationsummary?
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