How to use html.ValidationMessageFor

2020-05-18 23:34发布

I'm trying to get my view to give me the error message next to the text box if a user enters something invalid (like a string where it's expecting a number). Instead, I'm getting an ugly error page saying validation failed when the user presses submit.

Here is a portion of my view:

@model MembershipTest.ViewModels.AddDriverViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Add Drivers";
}

@using (Html.BeginForm("AddDriver", "Driver"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
<legend>Customer Information</legend>
 <table>
     <tr>
         <td>
             @Html.Label("First Name:")
             @Html.TextBoxFor(m => m.Driver.F_Name)
             @Html.ValidationMessageFor(m => m.Driver.F_Name)
         </td>
         <td>
             @Html.Label("Gender:")

             @Html.RadioButtonFor(m => m.isMaleChecked, "true") Male
             @Html.RadioButtonFor(m => m.isMaleChecked, "false")Female
         </td>
     </tr>
     <tr>
         <td>
             @Html.Label("Last Name:")
             @Html.TextBoxFor(m => m.Driver.L_Name)
             @Html.ValidationMessageFor(m => m.Driver.L_Name)
         </td>

And here is the relevant portion of my model:

[Required]
[StringLength(30)]
public string F_Name { get; set; }

[Required]
[StringLength(30)]
public string L_Name { get; set; }

In the post method of my controller, I make sure to use

if (ModelState.IsValid)

If the user happened to enter something like 50 characters long in the first name text box, I want an error to be displayed using the Html.ValidationMessageFor() right when they tab out of that text box, so they can see it before they press submit. Am I missing some jquery to make this happen? Maybe some using statement I need to include?

1条回答
Animai°情兽
2楼-- · 2020-05-19 00:04

It was silly simple.....I just didn't add the ErrorMessage field as part of the [Required] decorator. For example:

[Required(ErrorMessage = "First name is required")]
[StringLength(30, ErrorMessage = "Name can be no larger than 30 characters")]
public string F_Name { get; set; }

[Required(ErrorMessage = "Last name is required")]
[StringLength(30, ErrorMessage = "Name can be no larger than 30 characters")]
public string L_Name { get; set; }

Now, if a user either doesn't enter anything in the name fields, or enters something over 30 characters, the Post method doesn't get executed and the user gets a little message telling them what's wrong.

查看更多
登录 后发表回答