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
- How to add two numbers in Android Studio? | Source Code
- FindViewByID returns null in android studio -SOLVED
- Saving changes is not permitted in SQL SERVER - [SOLVED]
- Restore of database failed. File cannot be restored over the existing. -[SOLVED]
- One or more projects in the solution were not loaded correctly in Visual Studio 2019 | FIXED
- How to find Laptop's Battery Health?
- SOLVED-Related Field got invalid lookup: icontains error in Django
- How to enable Search Feature in Django admin?
Related Article