0
<div class="editor-field">
    @Html.TextBox("manager-control", "", new { id = "manager-control", @class = "form-control", placeholder = "Type to search..." })
    @Html.HiddenFor(model => model.manager, new { id = "manager-dn" })
    @Html.ValidationMessageFor(model => model.manager)
</div>

manager-control is an autocomplete, autocomplete select handler adds a value to the hidden field which represents the value for the manager. I can enable the validation message for the hidden field, that's fine, but the validation message itself is displayed outside the form.

I'd like to display the message itself on the manager-control element. What would be the best way to do that? The manager-dn field MUST have a value when the form is submitted, so simply saying that the manager-control should be filled out will not work.

The two ways I can think of are to use LabelFor instead of HiddenFor, and thus display an ugly text string, or find a way to display the validation message above the input.

EDIT:

This is useful in situations where you don't want to display the value of the selected AutoComplete item to the user but do want to validate that something has been selected.

1
  • Constructive feedback for downvote please, don't just driveby. Commented Oct 31, 2014 at 12:58

1 Answer 1

1

As far as I've found, there's no way to actually change which element the validation message displays next to.

My solution:

<div class="editor-field">
    @Html.TextBoxFor(model => model.manager, new { id = "manager-dn", @class="form-control", style="position:absolute;z-index:-1;" })
    @Html.TextBox("manager-control", "", new { id = "manager-control", @class = "form-control", placeholder = "Type to search..." })                        
    @Html.ValidationMessageFor(model => model.manager)
</div>

This hides the TextBoxFor behind the AutoComplete textbox. It retains the form-control class as without it, there are some CSS attributes that are missed out and the validation message will not display in the same place.

That being said, changing the z-index will also mean it no longer automatically fills to the size of its container. This can be fixed by using jQuery or JavaScript to programmatically set the width to that of the element it's hidden behind, in this case;

$('#manager-dn').width($('#manager-control').width());
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.