In this article, I will show you how to display images along with Validation message using dataannotations in mvc asp.net c#.
Here, I want to check the string length for the CategoryName using the ErrorMessage property of StringLength attribute along with HTML markup tag.
Category class: custom validation in mvc for CategoryName property.
public partial class Category
{
public int CategoryID { get; set; }
[Required]
[StringLength(15, ErrorMessage = "<imgsrc='/Images/error.png' /> category name should not exceed the max lengththan 15!")]
public string CategoryName { get; set; }
public string Description { get; set; }
}
Create view: asp.net mvc form validation
<fieldset>
<legend>Category</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CategoryName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CategoryName)
@Html.Raw(HttpUtility.HtmlDecode(
@Html.ValidationMessageFor(model=> model.CategoryName).ToHtmlString()))
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
In the create view we should decode the plain string using HtmlDecode() method in HttpUtility object and also use Html helper Raw to return HtmlString.
If there any a validation error you can show using ValidationMessageFor, it will display a message along with the image.
MVC Validation example:
Post your comments / questions
Recent Article
- ModuleNotFounEerror:No module named celery in Django Project
- How to get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
Related Article