阻止不引人注目的验证触发特定的提交按钮

Stop unobstrusive validate from triggering for specific submit buttons

我的页面上有几个 input 类型的 submit 字段。对于其中一些,我希望验证正常进行,但对于其他我不希望。每个 submit 按钮将表单发送回控制器,为每个按钮设置一个命令值。这允许动作执行相关功能。但是,如果我将 class cancel 添加到相关的 input 标记,则不会对它们进行验证。但是后来我没有得到回传到控制器操作的命令的值。所以我可以不验证或获取命令值,但不能两者都验证。

设置;

型号;

public void SubData
{
    public int ID { get; set; }
}

public void SomeViewModel
{
    public int ID { get; set; }
    public List<SubData> Data { get; set; }
}

在HTML;

<input type="submit" name="command" value="AddData" />
<input type="submit" name="command" value="DeleteData/>
<input type="submit" name="command" value="SaveAll/>

控制器;

public ActionResult Index(SomeViewModel model, string command)
{
    switch (command)
    {
        case "AddData":
            model.Stuff.Add(new SubData());
            break;
        case "DeleteData":
            // you get the idea...
            break;
    }
}

Javascript(摘自:);

$(function () {
    // allow delete actions to trigger a submit without activating validation
    $(document).on('click', 'input[type=submit].cancel', function (evt) {
        // find parent form, cancel validation and submit it
        // cancelSubmit just prevents jQuery validation from kicking in
        $(this).closest('form').validate().cancelSubmit = true;
        $(this).closest('form').submit();
        return false;
    });
});

因此,如果我有 <input type="submit" class="cancel" value="AddSomething" />,则验证不会发生(耶!)但我没有在操作的参数 command 中提供任何值(嘘!)。取出 cancel 会触发验证,验证成功后我会得到 command 的值。

尝试使用evt.preventDefault()来防止提交此输入

$(function () {
    // allow delete actions to trigger a submit without activating validation
    $(document).on('click', 'input[type=submit].cancel', function (evt) {
        //use  the preventDefault() to stop any submition from here
        evt.preventDefault();
        // find parent form, cancel validation and submit it
        // cancelSubmit just prevents jQuery validation from kicking in
        $(this).closest('form').validate().cancelSubmit = true;
        $(this).closest('form').submit();
        return false;
    });
});