ModelState.AddModelError to a particular ValidationMessageFor of a field?

非 Y 不嫁゛ 提交于 2019-12-10 19:42:28

问题


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?


回答1:


You need to provide a key:

ModelState.AddModelError("ImageUpload", "Invalid image file.");



回答2:


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.



来源:https://stackoverflow.com/questions/21820236/modelstate-addmodelerror-to-a-particular-validationmessagefor-of-a-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!