Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.AddModelError to a particular ValidationMessageFor of a field?

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?

like image 725
ca9163d9 Avatar asked Feb 17 '14 03:02

ca9163d9


2 Answers

You need to provide a key:

ModelState.AddModelError("ImageUpload", "Invalid image file.");
like image 178
Brendan Green Avatar answered Nov 13 '22 04:11

Brendan Green


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.

like image 26
randyh22 Avatar answered Nov 13 '22 03:11

randyh22