Validate.unobtrusive并验证jQuery库

时间:2012-06-25 10:28:06

标签: jquery asp.net-mvc-3

我正在构建一个MVC 3应用程序,它使用标准的模型验证属性进行基本的客户端和服务器验证。但是我也有一个表头,它在头文件中并使用jQuery validate插件来执行客户端验证。

当我将不显眼的库添加到项目时,使用validate插件的标题表单无法运行并继续发布。当不包含不显眼的库时,标题验证正常,但模型验证停止。

知道我做错了吗?

修改

基本上我在标题中有一个登录表单。我还有一个登录页面,也允许登录。登录页面与模型绑定,但标题中的表单不是,它只是html。两种形式都通过jQuery .ajax调用相同的Controller / Action。

我已经失去了使用.ajax方法的能力,因为我包含了不显眼的库,所以它似乎没有被调用。

我获得了您所使用的代码,但在验证完成后我仍然无法发布或执行操作。

我的标题表单是:

<form id="frmHeaderLogin" action="">
<table id="LoginBox" title="Login">
    <tr>
        <td>UserName</td>
        <td><input type="text" id="Username" name="Username" /></td>
    </tr>
    <tr>
        <td>Password</td>
        <td><input type="password" id="Password" name="Password" /></td>
    </tr>
    <tr>
    <td colspan="2"><input type="submit" value="Login" id="btnHeaderLogin" name="btnHeaderLogin" /></td>
    </tr>
</table>
</form>

我有一个提交按钮的click事件,它将验证客户端输入,然后在创建JSON对象作为数据参数后将其提交给服务器。服务器的响应也是JSON对象。此表单位于布局文件中,因为它将出现在每个页面上。

主登录页面/视图的格式如下:

@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "MainLoginForm" }))
{
<div>
    <fieldset>
       <p style="color:Red;font-size:medium">@ViewData["Message"]</p>
        <legend>Login</legend>
        <div class="editor-label">
        @Html.LabelFor(m => m.UserName, "EmailId")
        </div>
        <div class="editor-field">
        @Html.TextBoxFor(m => m.UserName)
        @Html.ValidationMessageFor(m => m.UserName)
        </div>
        <div class="editor-label">
        @Html.LabelFor(m => m.Password, "Password")  
        </div>
        <div class="editor-field">         
        @Html.PasswordFor(m => m.Password)
        @Html.ValidationMessageFor(m => m.Password)
        </div>
        <p>
        <input type="submit" id="btnMainLogin" value="Login" />
        </p>
     </fieldset>
</div>
}

这也有一个jQuery click事件,它触发.ajax方法并将JSON对象发布到服务器,如上所述。两个实例都返回一个JSON对象。

我想在这一点上问题可能是,我可以在布局文件中使用相同的模型登录,这将允许我使用客户端和服务器验证吗?

以下是验证通过后我使用的submitHandler示例(使用jquery.validate)

    $("#formname").validate( {
     // .....
         // .....
         submitHandler: function () {
            var JSONData = new Object();
            $(':text, :password', $("table[id$='LoginBox']")).each(function () {
                JSONData[$(this).attr("id")] = $(this).val();
            });

            $.ajax({
                type: "POST",
                url: "/Controller/Action",
                data: "{'Login': '" + JSON.stringify(JSONData) + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    var response = $.parseJSON(result);
                    alert("Header Login Success!");
                },
                error: function (xhr, status, error) {
                    alert(xhr.statusText + " - ReadyState:" + xhr.readyState + "\n" + "Status: " + xhr.status);
                }
            });
         }
    )};

1 个答案:

答案 0 :(得分:6)

如果要将Microsoft不显眼验证脚本与您在同一页面中编写的自定义jquery验证规则混合使用,则需要将jquery验证规则添加到现有表单元素。我们来举个例子:

public class MyViewModel
{
    [Required]
    public string Foo { get; set; }

    public string Bar { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

查看:

@model MyViewModel

<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 type="text/javascript">
    $(function () {
        $('#Bar').rules('add', {
            required: true,
            messages: {
                required: 'Bar is required'
            }
        });
    });
</script>

@using (Html.BeginForm())
{
    <div>
        @Html.EditorFor(x => x.Foo)
        @Html.ValidationMessageFor(x => x.Foo)
    </div>

    <div>
        @Html.EditorFor(x => x.Bar)
        @Html.ValidationMessageFor(x => x.Bar)
    </div>

    <button type="submit">OK</button>
}

注意Foo字段的Required属性如何使其成为必需,我们已经为Bar字段定义了自定义jquery验证规则。

以下是提交表单并将2个字段留空时的结果:

enter image description here

您当然可以在任何字段上定义任意数量的自定义规则。

相关问题