【问题标题】:jQuery validation is not working with ASP .Net MVC data annotationsjQuery 验证不适用于 ASP .Net MVC 数据注释
【发布时间】:2017-05-30 02:00:41
【问题描述】:

我正在开发一个 ASP .Net MVC 4 Web 应用程序。在这里,我尝试使用 jQuery 的验证和不显眼的插件来实现验证。示例代码如下所示

注册模式

public class Signup
{

    [StringLength(256,ErrorMessage ="Name can have maximum of 256 characters.")]
    [Required]
    public string Name { get; set; }

    [Required]
    [StringLength(10, ErrorMessage = "User code should have of 10 character.", MinimumLength = 10)]
    public string UserCode { get; set; }

[StringLength(256, ErrorMessage = "Password can have maximum of 256 characters.")]
    [Required]
    public string Password { get; set; }

    [StringLength(256, ErrorMessage = "Confirm Password can have maximum of 256 characters.")]
    [Required]
    public string ConfirmPassword { get; set; }
}

Signup.cshtml

 @using (Html.BeginForm("SubmitSignUp", "Foobbox", Model, FormMethod.Post)) {
    @Html.ValidationSummary()
        <span class="input-group-addon">
            <i class="material-icons">face</i>
        </span>
        @Html.EditorFor(x => x.Name, new { @class="form-control", @placeholder = "Name"})
        @Html.ValidationMessageFor(x => x.Name)                                           
    </div>

    <div class="input-group">
        <span class="input-group-addon ">
            <i class="material-icons">email</i>
        </span>
        @Html.TextBoxFor(x => x.EmailId, new { @class = "form-control", @placeholder = "Email" })
        @Html.ValidationMessageFor(x => x.EmailId)                                           
    </div>
}

&lt;head&gt;标签下

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

上面指定的验证是在 HTML 中生成数据验证属性

例如:

<input class="text-box single-line" data-val="true" data-val-length="Name can have maximum of 256 characters." data-val-length-max="256" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="">

问题是我无法向用户显示相应的错误消息。有什么我想念的吗?还是我做错了什么?

【问题讨论】:

  • 那么当你提交表单时会发生什么?
  • 因为我正在检查模型在我的控制器中是否有效,所以它不接受请求。所以基本上什么都没有发生
  • 你的意思是它不接受请求 ??您的表单提交了吗?
  • 是的,正在提交表单。但正如我已经说过的,控制器只有在提交的模型有效时才会接受请求。
  • @Sasu 您是否在 web.config 中启用了客户端验证密钥

标签: asp.net-mvc asp.net-mvc-4 data-annotations unobtrusive-validation


【解决方案1】:

在 web.config 中启用 ClientValidationEnabled 键。

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

【讨论】:

    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多