简体   繁体   中英

Razor @Html.ValidationMessageFor() not displaying “validation error message”

@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; }

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM