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!