ModelState.AddModelError is not being displayed inside my view
Solution 1:
I would urge you to change your try{ } catch(){ }
And first check if there exists a visit for the given id and if so simply returns the model with the added model error
if (visitExists)
{
ModelState.AddModelError("CustomError", "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
return View(vlr);
}
//Other code here
Change your AddModelError To
ModelState.AddModelError("CustomError", "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
And in your view simply add a
@Html.ValidationMessage("CustomError")
Then when you return your model the error will be shown where you have placed the @Html.ValidationMessage ...
Solution 2:
@Html.ValidationSummary(true)
shows only the error message about model's propertys, if you want to show also the added message, added with
ModelState.AddModelError(
"CustomError",
"The Same test Type might have been already created, go back to the Visit page to see the avilalbe Lab Tests");
you need to set
@Html.ValidationSummary(false)
If you need to display the validation's message near your input fields you need to set @Html.ValidationSummary(true)
and to follow the steps suggested by Syneryx
Solution 3:
You can use from ViewData
dictionary in View to access ModelState
data.
For example:
in Action:
ModelState.AddModelError("CustomError", "Error 1");
ModelState.AddModelError("CustomError", "Error 2");
and to get "Error 1" message:
ViewData.ModelState["CustomError"].Errors[0].ErrorMessage