简体   繁体   中英

Client-side validation not working from data annotations; server-side does

I'm having trouble getting client validation to work on a web form. I'm including .js files and have the relevant lines in web.config, but data validation doesn't get put into the HTML on the client side.

My layout, which is being applied to the page, looks like

<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>

My web.config file has the following:

<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="webpages:Enabled" value="false" />
</appSettings>

My page's viewmodel has proper annotations and is being validated properly on the server-side

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

Finally, I am including the following HTML in my page:

<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>

The HTML output by the page at this section looks like:

<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>

I'm about at my wit's end with this. Any help would be greatly appreciated!

You should wrap these code in 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>
}

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