【问题标题】:ajax mvc html: jquery val not preventing call to apiajax mvc html:jquery val 不阻止调用 api
【发布时间】:2018-02-25 20:29:46
【问题描述】:

单击按钮时,我正在使用 ajax 调用 Web api。根据我的视图模型数据注释,我的表单使用 JqueryVal 进行表单验证。

我的问题是,当我单击表单中的“Listo”按钮时,它会调用我的 API,尽管 jqueryval 正在标记错误(需要选择文件)

这是我的代码:

包含数据注释的我的视图模型(数据注释与jquery.validate.jsjquery.validate.unobtrusive.js 一起使用。如您所见,它正在工作,但不会阻止调用API):

public class CursoViewModel
{
    public Guid Id { get; set; }
    [MaxLength(125)]
    public string Titulo { get; set; }
    [Required]      
    public string Descripcion { get; set; }
    [Required(ErrorMessage ="selecciona una imagen para tu curso")]
    [DataType(DataType.Upload)]
    public HttpPostedFileBase Imagen { get; set; }
}

类发布到我的 api

public class person
{
    public string name { get; set; }
    public string surname { get; set; }
}

API 代码

[HttpPut]
[Route("api/ProfesorCurso/test")]
public string Put(person p)
{
    return p.name + p.surname;
}

我的观点

@model project.ViewModels.CourseViewModel
<form id="Editcurso" method="post" action="#">
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "Please fix the following errors.")
    <div class="container">
        <div class="form-group">
            @Html.LabelFor(c=>c.Titulo)
            @Html.TextBoxFor(c => c.Titulo, new {id="titulo", @class="form-control"})           
            @Html.ValidationMessageFor(m => m.Titulo)
        </div>
        <div class="form-group">
            @Html.LabelFor(c => c.Descripcion)
            @Html.TextAreaFor(c => c.Descripcion, new {id="descripcion", @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Descripcion)
        </div>
        <div class="thumbnail" id="imagencurso"></div>
        <div class="form-group">
            @Html.LabelFor(m => m.Imagen)
            @Html.TextBoxFor(m => m.Imagen, new {id="imagen" ,type = "file", data_rule_validCustomer = "true" })
            @Html.ValidationMessageFor(m => m.Imagen)
        </div>
        <button id="submiter" type="submit" class="btn btn-primary">Listo!</button>
    </div>
</form>

视图中的脚本

@section scripts
{
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        $(document).ready(function () {
            $("#submiter").click(function () {
                jQuery.support.cors = true;
                var person = new Object();
                person.name = "Sourav";
                person.surname = "Kayal";
                $.ajax({
                    url: '/api/ProfesorCurso/test',
                    type: 'PUT',
                    dataType: 'json',
                    data: person,
                    success: function (data) {
                        console.log(data);
                        return false;
                    },
                    error: function (x, y, z) {
                        alert('error al postear');
                        return false;
                    }
                });
            });
        });
    </script>
}

如果出现 Jquery 验证错误,我该怎么做才能防止 ajax 在单击我的表单按钮时调用我的 api?

谢谢

【问题讨论】:

    标签: javascript jquery html ajax asp.net-mvc


    【解决方案1】:

    您应该处理表单的.submit() 事件,然后您可以检查.valid(),如果没有则取消ajax 调用。请注意,您还应该取消默认提交。

    $('#Editcurso').submit(e) {
        e.preventDefault(); // prevent the default submit
        if (!$(this).valid()) {
            return; // exit the function and display the errors
        }
        ....
        $.ajax({
            ....
        });
    }
    

    附带说明一下,添加 new { id="titulo" } 等是没有意义的 - 生成表单控件的 HtmlHelper 方法已经根据属性名称添加了 id 属性

    【讨论】:

    • 哇!这太好了!经过两天的尝试和尝试,我成功了!!!谢谢
    • 很高兴,但我仍然对您在这里实际所做的事情感到有些困惑-您的观点基于CourseViewModel,但您发回了person 的数据-您在哪里提交数据CourseViewModel?
    • 我以 person 为例来简化我的调试。我这样做是因为我无法使用 AJAX 正确调用我的 api。实际上我并没有以“正常”的方式发回任何东西(这意味着我发回一个 mvc 控制器),我只是使用 ajax 来更新或发布东西到我的后端。
    猜你喜欢
    • 2011-11-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多