I would like to reduce the following code. The below code works, however it is not very tidy etc.
<label for="Name">Name:</label><%= Html.TextBox("Name")%><%
if (!string.IsNullOrEmpty(Html.ValidationMessage("Name"))) {
string Error = HtmlRemoval.StripTags(Html.ValidationMessage("Name")); %>
<img src="Error.gif" alt="Error" title="<%= Error %>" /><%
}
%>
I have read that I need to extend the Html helper so that I can return an image instead of the text containing the default element and textual error.
I can’t seem to find any articles or general advice on how I would accomplish this. I am still very new to ASP.NET MVC. Any advice would be greatly appreciated.
You can extend HtmlHelper like:
Then in your page import the class containing the extension method
Then add the following to your page:
For more on extending HtmlHelper try here but basically this extends HtmlHelper, checks the ViewState for a an error on the value parsed in name (“Name” in your case) and if it contains an error generates the HTML needed to render the image. The title attribute for the image will contain the validation message for field “Name”