ASP.NET MVC 3不显眼的验证 - 验证事件之前? [英] ASP.NET MVC 3 Unobtrusive Validation - Before Validate Event?

查看:234
本文介绍了ASP.NET MVC 3不显眼的验证 - 验证事件之前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ASP.NET MVC3的不显眼的验证功能,我怎么能验证运行之前运行一些JavaScript? jQuery的提交处理程序验证出于明显的原因后运行。我可以钩到提交按钮点击,但似乎并不很优雅。有什么建议?

Using ASP.NET MVC3's unobtrusive validation feature how can I run some JavaScript before validation runs? Jquery's submit handler runs after validation for obvious reasons. I can hook into a click on the submit button but that doesn't seem very elegant. Any suggestions?

修改

看来我上面的说法是不正确。正如指出提交处理下面没有验证之前运行。不幸的是,这并不解决我的问题。

It appears my above statement is incorrect. As was pointed out below the submit handler does run before validation. Unfortunately that does not solve my problem.

我的修订问题:

我需要处理表单提交之后,但jQuery验证前一种形式的价值。如果我使用jQuery的提交处理程序提交后更改值,然后jQuery的验证原始值而不是新值。

I need to manipulate a form value after form submission but before jQuery validation. If I change the value after submission using jQuery's submit handler then jQuery validates the original value not the new value.

推荐答案

在提交处理后,确认不运行。它之前运行。试试吧:

The submit handler doesn't run after validation. It runs before. Try it:

$('form').submit(function () {
    alert('validation hasn\'t run yet at this point => see there is no red color over your form input fields yet');

    if ($(this).valid()) {
        alert('the form is valid');
    } else {
        alert('the form is not valid');
    }
});


更新:

在修订后的问题,我仍然无法重现该问题。这里是我的模型:

After the revised question I am still unable to reproduce the issue. Here's my model:

public class MyModel
{
    [Required]
    public string Name { get; set; }
}

这是我的看法:

@model MyModel

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

@using (Html.BeginForm(null, null, FormMethod.Post, new { }))
{
    @Html.EditorFor(x => x.Name)
    @Html.ValidationMessageFor(x => x.Name)
    <input type="submit" value="OK" />
}

<script type="text/javascript">
    $('form').submit(function () {
        $('#Name').val('some value');
    });
</script>

现在,如果我离开名称字段留空并提交表单,新的价值正在被正确地分配和表单成功提交给服务器没有任何错误。如果我删除 $('#名称)VAL('某个值'); 行分配一个新的价值,并尝试用空场客户端提交表单端验证触发器和形式没有提交。

Now if I leave the Name field blank and submit the form, the new value is being properly assigned and the form is successfully submitted to the server without any errors. If I remove the $('#Name').val('some value'); line that assigns a new value and try to submit the form with an empty field client side validation triggers and the form is not submitted.

这篇关于ASP.NET MVC 3不显眼的验证 - 验证事件之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆