我无法在网络表单上进行客户端验证。我包含.js文件并在web.config中有相关的行,但是数据验证不会放到客户端的HTML中。
我的布局正在应用于页面,看起来像
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript" ></ script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript" ></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript" ></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript" ></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
</head>
我的web.config文件包含以下内容:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="webpages:Enabled" value="false" />
</appSettings>
我的网页的viewmodel有正确的注释,并且正在服务器端正确验证
[DisplayName("Url")]
[DataType(DataType.Url, ErrorMessage = "Invalid Url")]
[StringLength(30)]
[Required]
public string url { get; set; }
[DisplayName("Email")]
[DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email Address")]
[Required]
public string email { get; set; }
最后,我在我的页面中包含以下HTML:
<div class="conLine">
@Html.LabelFor(m=> m.url): @Html.TextBoxFor(m => m.url)
@Html.ValidationMessageFor(m => m.url)
</div>
<div class="conLine">
@Html.LabelFor(m=> m.email): @Html.TextBoxFor(m => m.email)
@Html.ValidationMessageFor(m => m.email)
</div>
此部分页面的HTML输出如下所示:
<div class="conLine">
<label for="url">Url</label>
:
<input class="input-validation-error" id="url" name="url" type="text" value=""/>
<span class="field-validation-error">The Url field is required.</span>
</div>
我的机智就此结束了。任何帮助将不胜感激!
答案 0 :(得分:3)
您应该将这些代码包装在Html.BeginForm
中@using (Html.BeginForm()) {
<div class="conLine">
@Html.LabelFor(m=> m.url): @Html.TextBoxFor(m => m.url)
@Html.ValidationMessageFor(m => m.url)
</div>
<div class="conLine">
@Html.LabelFor(m=> m.email): @Html.TextBoxFor(m => m.email)
@Html.ValidationMessageFor(m => m.email)
</div>
}