如何使用html.ValidationMessageFor [英] How to use html.ValidationMessageFor
问题描述
我试图让我的看法,如果用户输入无效的东西(比如它的预期数字的字符串)给我的错误信息旁边的文本框。相反,我得到一个丑陋的错误页面,指出验证失败当用户presses提交。
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)
如果用户发生在名字文本框输入像长50个字符,我想用Html.ValidationMessageFor(显示错误),权当他们标签指出,文本框,这样他们就可以看到它他们之前$ $ p PSS提交。我缺少一些jQuery做到这一点?也许有些using语句我需要包括哪些内容?
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?
推荐答案
这是愚蠢的简单.....我只是没了的ErrorMessage字段添加为[必填]装饰的一部分。例如:
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; }
现在,如果用户要么不中的名称字段输入任何内容,或者进入一些超过30个字符,邮政法没有得到执行,用户变得有点消息,告诉他们什么是错的。
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.
这篇关于如何使用html.ValidationMessageFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!