0

I have following code in Razor view:

@using (Html.BeginForm("Edit", "Person", FormMethod.Post, new { ... }))
{
    ...
    <div class="field">
        @Html.LabelFor(m => m.FirstName, "Firstname")
        @Html.TextBoxFor(m => m.FirstName</div>)
        @Html.ValidationMessageFor(m => m.FirstName)
    </div>
    <div class="field">
        @Html.LabelFor(m => m.LastName, "LastName")
        @Html.TextBoxFor(m => m.LastName</div>)
        @Html.ValidationMessageFor(m => m.LastName)
    </div>
    <div class="field">
        @Html.LabelFor(m => m.PhoneNumber, "PhoneNumber")
        @Html.TextBoxFor(m => m.PhoneNumber)
        @Html.ValidationMessageFor(m => m.PhoneNumber)
    </div>
    ...
}

When form gets posted, controller does validation and populates ModelState (dictionary) with error messages for those fields that are required but missing. These error messages are shown in a separate span next to the text boxes.

Now, instead of showing the error message as a separate span-element, I would rather like to set it as a title for the corresponding textbox (so that it shows as a tooltip).

I figure I will have to set the title of the textbox after POST returns and loop through all validation errors, so something like this:

foreach (KeyValuePair<TKey, TValue> pair in ViewState.ModelState)
{
    var k = pair.Key;
    var v = pair.Value;

    // Iterate over all errors and set the error
    // message as title for textbox
    foreach (var error in pair.Value.Errors)
    {
        // Ignore some keys...
        if(pair.Key != "ErrorMessageSummary")
        {
            // Find the element that was missing value and set title:
            $(@Html.IdFor(m => pair.Key)).prop({
                title: error.ErrorMessage,
            });
        }
    }
}

There is a JavaScript function that gets called when user clicks 'save'-button:

$('#save').on('click', function (e) {
    submitForm('@Url.Action("Save", "Person")', '@formId', '@waitMessage', '@successMessage');
    return false;
});

Being a novice in JavaScript and Razor, I can't quote figure this out.

Questions

  • How do I do this?
  • Where do I do this?

Thanks!

2
  • have a look at following link, it might help : codeproject.com/Articles/1042984/… Commented Mar 30, 2017 at 18:46
  • Thanks! I looked your example and did it like that. My question was also asked in stackoverflow.com/questions/8380988/…. What I couldn't quite figure out is how to replace that asterisk '*' (as a tip-trigger) in inner HTML with an image instead. Also, I don't want to show the asterisk/image if there is no validation error. Commented Mar 31, 2017 at 8:23

0

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.