5
@Html.RequiredLabelFor(x => x.FirstName)
@Html.TextBoxFor(model => model.FirstName, new { Name = "1.first_name", tabindex = "1" })
@Html.ValidationMessageFor(model => model.FirstName)

Is there a reason why when passing second parameter to @Html.TextBoxFor the field is being validated but "validation message" does not appear?

@Html.RequiredLabelFor(x => x.FirstName)
@Html.TextBoxFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)

When using an overload that accepts only one argument (lambda expression) "validation message" is being displayed correctly.

In my understanding the actual property is not being recognized?

Backing property:

[StringLength(100, ErrorMessage = "Max length 100 characters")]
[Required(ErrorMessage = "This field is required")]
[Display(Name = "First name")]
public string FirstName { get; set; }

2 Answers 2

12

The unobtrusive validation library identifies 'things to display validation for' using the name attribute. It's not that specifying extra properties stops it from working, but you have changed the name property and not reflected the new name in your validation helper.

You can either stop changing the name attribute in your textbox helper (necessary if you use the default model binder to return your view), or you can use

@Html.ValidationMessage("1.first_name")

The above method is not a good idea unless you're using JS/JQuery to validate and submit your form data (via AJAX), for the reasons given by Stephen in comment to this answer.

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

1 Comment

Do not use @Html.ValidationMessage("1.first_name"). Not only does this mean that all model binding is lost when you post back, if the view is returned, the ModelState error will never be displayed for this property
6

You have changed the name attribute, so not only will it not post back and bind to your model, jquery.validate.unobtrusive can now no longer match up the controls since the input has a different name than the associated validation message

<input name="1.first_name" ... />
<span .. data-valmsg-for="FirstName" ..></span> // There is no control named FirstName

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.