I have the following code to generate an html input and validation message.
@Html.ValidationSummary(false)
......
<div class="col-md-10">
@Html.TextBoxFor(model => model.ImageUpload, new { type = "file", name = "file" })
@Html.ValidationMessageFor(model => model.ImageUpload)
</div>
In my action I have the code
if (.... something wrong with the input ....)
{
ModelState.AddModelError("", "Invalid image file.");
return RedirectToAction(....
However, it will show an error message in the validation summary section. Is it possible to show the error message in the validation message section for input too?
You need to provide a key:
ModelState.AddModelError("ImageUpload", "Invalid image file.");
This doesn't exactly answer the OPs original question, but what I was looking for was the ability to add a model error to the ModelState for a control on my form that was not part of the model. The way to do that is to add a ValidationMessage helper to the page which you can reference in the AddModelError call by name. Example:
@Html.ValidationSummary(false)
......
<div class="col-md-10">
<input name="FileName" />
@Html.ValidationMessage("FileNameValidation")
</div>
Then, in your controller action, you can do:
if (.... something wrong with the input ....)
{
ModelState.AddModelError("FileNameValidation", "Please fix the File Name.");
return View( viewModel );
}
Hope this helps someone with a slightly different situation.
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