【问题标题】:Prevent ajax form to call server on client side errors防止ajax表单在客户端错误上调用服务器
【发布时间】:2014-03-06 01:29:46
【问题描述】:

我有一个表单,我在提交按钮上使用它来获取一些值并返回带有这些值的部分。

在页面中,我包含了 jquery 验证和不显眼的 .. 在客户端进行验证,这很好,它验证了,但仍然调用服务器,我该如何避免它?

@using (Html.BeginForm("Index", "Search", FormMethod.Post, new { role = "form", @class = "form-horizontal", id = "SearchForm" }))
{
    @Html.AntiForgeryToken();
    @Html.EditorFor(m => m.Test);

    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-default">@Base.Search</button>
        </div>
    </div>
}               

@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")

$('#SearchForm').on('submit', function (evt) {
    evt.preventDefault();
    $.post('/Search/Index', $(this).serialize(), function (response) {
        $('#searchResults').html(response);
    });
});

这是我的控制器

[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Index(SearchModel searchModel)
{
    if (ModelState.IsValid)
    {
        return PartialView("SearchResults", searchModel);
    }

    return null;
}

【问题讨论】:

  • 这个客户端验证在哪里?
  • 有的,忘记复制了)

标签: jquery ajax forms asp.net-mvc-3 validation


【解决方案1】:

你试过了吗

$('#SearchForm').on('submit', function (evt) {
    evt.preventDefault();

    if(!$(evt.currentTarget).valid())
        return false;

    $.post('/Search/Index', $(this).serialize(), function (response) {
        $('#searchResults').html(response);
    });
});

但必须只是 jquery 验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-18
    • 2016-03-03
    • 1970-01-01
    • 2015-03-29
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多