gpt4 book ai didi

asp.net-mvc - ASP.NET MVC Unobtrusive 客户端验证不起作用

转载 作者:行者123 更新时间:2023-12-01 18:06:32 25 4
gpt4 key购买 nike

在我的 ASP.NET MVC 4 应用程序中,我尝试使用流畅的验证来进行不显眼的客户端验证。

<script src="/Scripts/jquery.validate.min.js" type="text/javascript">
</script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript">
</script>

创建新的 ASP.NET MVC 4 应用程序时,我有 VS2010 提供的这两个 .js 文件。我还在我的 web.config 文件上启用了客户端验证。

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

据我所知,当启用客户端验证和不显眼的 JavaScript 时,具有客户端验证规则的输入字段包含 data-val="true"属性以触发不显眼的客户端验证。我的输入字段中有这些字段。

例如,

<input class="input-validation-error" data-val="true" data-val- 
required="error text here" id="purchasePrice"
name="PurchasePrice" type="text" value="">

<span class="field-validation-error error" data-valmsg-for="PurchasePrice"
data-valmsg-replace="true">'Purchase Price' must not be empty.</span>

但是,当我提交表单时,它会发布到 Controller ,并且在 Controller 代码而不是客户端上检查我的模型。

编辑:

这是我的表单开始标记。

@using (Html.BeginForm("Create", "Product", FormMethod.Post, 
new { enctype = "multipart/form-data", @class = "mainForm",
@id = "productCreateForm" }))

有什么想法吗?谢谢。

最佳答案

你添加了MVC的配置吗?

protected void Application_Start() {
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

// this line is required for fluent validation
FluentValidationModelValidatorProvider.Configure();
}

您还需要配置每个 View 模型/验证器:

[Validator(typeof(PersonValidator))]
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}

public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}

如果这没有帮助,您可以发布一个无法正常工作的验证器示例吗?并非所有验证都可以在客户端完成。例如,以下验证器仅在服务器端工作:

// when validator rules are always server side
public class ServerSideValidator : AbstractValidator<Person> {
public ServerSideValidator() {
When(x => x.Name == "Foo", () => {
RuleFor(x => x.Email).EmailAddress();
});
}
}

关于asp.net-mvc - ASP.NET MVC Unobtrusive 客户端验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11671724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com