在MVC3使用JavaScript验证表单 [英] validating form in MVC3 using javascript

查看:123
本文介绍了在MVC3使用JavaScript验证表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要一个验证的例子。剩余我会做。比方说,我有文本类型的输入:

I just need example for one validation. For remaining I will do. Let's say I have an input of type text:

 <p>                          
<label for="ClientName">ClientName:</label> <%= Html.TextBoxFor(model => model.Name)%>         
 </p>        

在这里,我想验证为必填字段文本框。我想在JavaScript中这个领域需要验证的功能,我想在视图中使用这个脚本。

Here I want to validate textbox for required field. I want this required field validation function in JavaScript and I want to use this script in the view.

推荐答案

你有使用不显眼的审定考虑?

Have you considered using unobtrusive validation?

你说你正在使用MVC3(虽然不是剃刀视图引擎显然)。

You say you are using MVC3 (although not the Razor view engine apparently).

通过您的code这样的:&LT; P&GT;&lt;用于=CLIENTNAME&GT的标签; CLIENTNAME:LT; /标签&gt; &LT;%= Html.TextBoxFor(型号=&GT; model.Name)%GT;&LT; / P&GT;
这可以写成
&LT; P&GT; @ Html.LabelFor(型号=&GT; model.Name)@ Html.TextBoxFor(型号=&GT; model.Name)LT; / P&GT; 在剃刀语法。​​

With your code like this: <p><label for="ClientName">ClientName:</label> <%= Html.TextBoxFor(model => model.Name)%></p> which could be written as <p>@Html.LabelFor(model=>model.Name) @Html.TextBoxFor(model => model.Name) </p> in Razor syntax.

如果你把这个在你的web.config:

If you put this in your web.config:

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

,然后用像这样的数据注解装饰模型中的属性:

and then decorate the property in your model with something like this data annotation:

[Display(Name = "Name")]
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }

然后通过添加以下到您的 _Layout.cshtml 文件,你会得到不显眼的审定工作:

Then by adding the following into your _Layout.cshtml file you will get unobtrusive validation to work:

<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<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>

然后,你可以添加这个地方的页面(要显示的验证消息)上: @ Html.ValidationMessageFor(型号=&GT; model.Name)

这篇关于在MVC3使用JavaScript验证表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆