8

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?

ca9163d9
  • 27,283
  • 64
  • 210
  • 413

2 Answers2

10

You need to provide a key:

ModelState.AddModelError("ImageUpload", "Invalid image file.");
Brendan Green
  • 11,676
  • 5
  • 44
  • 76
  • 5
    Nope, this doesn't work. Check out [this solution](http://stackoverflow.com/questions/12688082/validationmessagefor-together-with-addmodelerrorkey-message-whats-the-key). – Peter Sep 15 '16 at 19:22
  • 2
    The "key" is the name of the input field as specified in the `ValidationMessageFor` statement. – Suncat2000 Oct 16 '18 at 11:55
  • So loop through the error messages in the validation result then add each one like: ModelState.AddModelError(errorMessage.PropertyName, errorMessage.ErrorMessage) – Taraz Nov 22 '21 at 21:27
1

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.

randyh22
  • 463
  • 4
  • 10