Reputation: 225
How can I display ModelState
in my View? I have the following code for validation but I am not able to display Modelstate error in my View.
I have this conditions my action:
if (!ModelState.IsValid)
return BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage));
else if (ModelState.IsValid)
{
if (updatedProduct.ProductSRDate.Value > DateTime.Now)
ModelState.AddModelError("ProductSRDate", " Date must be current date or in the past.");
var PrjEditMode = await ProductService.GetProductsbyId(id);
var editMode = Mapper.Map<ProductDetails>(PrjEditMode);
return View(editMode);
}
In View I have Validation Summary as:
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
But it only display Date must be current date or in the past.
when there is a nullable field it display `Date must be current date or in the past.
0 "The value '' is invalid."
.
Upvotes: 2
Views: 6779
Reputation: 1627
You can Access ModelState class in view with the key :
Controller : ModelState.AddModelError("ProductSRDate", "Date must be current date or in the past.");
View : @Html.ValidationMessage("ProductSRDate")
But you're code logical error because you add an error to your ModelState
if IsValid
.
if (!ModelState.IsValid || updatedProduct.ProductSRDate.Value > DateTime.Now)
{
if (updatedProduct.ProductSRDate.Value > DateTime.Now)
{
ModelState.AddModelError("ProductSRDate", " Date must be current date or in the past.");
}
//return BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage));
return View(editMode); // You should return a view and handle Invalid ModelState in view.
}
else
{
var PrjEditMode = await ProductService.GetProductsbyId(id);
var editMode = Mapper.Map<ProductDetails>(PrjEditMode);
return View(editMode);
}
Upvotes: 2