1

I want to display an asterisk (*) next to a text box in my form when initially displayed (GET) Also I want to use the same view for GET/POST when errors are present) so For the GET request I pass in an empty model such as return View(new Person());

Later, when the form is submitted (POST), I use the data annotations, check the model state and display the errors if any Html.ValidationMessageFor(v => v.FirstName)

For GET request, the model state is valid and no messages, so no asterisk gets displayed. I am trying to workaround this by checking the request type and just print asterisk. @(HttpContext.Current.Request.HttpMethod == "GET"? "*" : Html.ValidationMessageFor(v=> v.FirstName).ToString())

The problem is that Html.ValidationMessageFor(v=> v.FirstName).ToString() is already encoded and I want to get the raw html from Html.ValidationMessageFor(v=> v.FirstName)

Or may be there is a better way here. 1. How do you display default helpful messages (next to form fields) - such as "Please enter IP address in the nnn.nnn.nnn.nnn format) for GET requests and then display the errors if any for the post? 2. What is the best way from a razor perspective to check an if condition and write a string or the MvcHtmlString

1
  • Have you tried creating your own custom HTML helper, overriding the behaviour of ValidationMessageFor with a new one like ValidationForMessageCustom HTML helper extension that in itself when rendered to the screen checks the current request context and prints the appropriate message? In the helper to make it even more extensible, you could pass a string that's printed for get requests such as "Please enter the IP in the format..." Commented May 26, 2013 at 9:46

1 Answer 1

1

Further to my last comment, here is how I would create that helper to be used:

    public static class HtmlValidationExtensions
    {
        public static MvcHtmlString ValidationMessageForCustom<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string customString)
        {
           var returnedString = HttpContext.Current.Request.HttpMethod == "GET" ? customString : helper.ValidationMessageFor(expression).ToString();

           return MvcHtmlString.Create(returnedString);
        }
    }

And it would be used like this @Html.ValidationMessageForCustom(v=> v.FirstName, "Please enter IP address in the nnn.nnn.nnn.nnn format")

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.