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
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
- FieldError: Cannot resolve keyword 'id' into field in Django project
Related Article