asp.net MVC Core - 使用Ajax加载局部视图

时间:2017-01-03 09:16:51

标签: ajax asp.net-mvc asp.net-ajax asp.net-core-mvc partial-views

在我的MVC Core应用程序中,我希望在提交表单后加载部分视图。

提交_TransferForm中的表单后,将加载另一个部分视图,而不是刷新整个页面。以下是我的代码。

为什么_ApplySuccess占据整个页面,而不是在Apply中显示为页面的一部分?

我在共享<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js">中添加了_Layout

父视图 Apply.cshtml

@Html.Partial("_ApplyForm")

@section Scripts {
  <script>
    // delegate submit event to document, since form might be replaced
    $(document).on('submit', '#applyForm', function () {
        var $theForm = $(this);
        // manually trigger validation
        if ($theForm.valid()) {
            $('#progress').show();
            $.post('', $theForm.serialize())
                .done(function (response) {
                    $theForm.replaceWith(response);
                })
        }
        return false;
    });
  </script>   
}

部分视图 _ApplyForm.cshtml

<form id="applyForm" asp-action="Apply" asp-controller="Jobs">
// content
</form>

部分视图 _ApplySuccess.cshtml

<div>Successfully applied.</div>

控制器的操作 Apply

    public async Task<IActionResult> Apply(Applicant applicant)
    {
        if (ModelState.IsValid)
        {
            // code

            return PartialView("_ApplySuccess");
        }
        return PartialView("_ApplyForm");
    }

2 个答案:

答案 0 :(得分:1)

您可以使用启动箱提醒来显示该流程已完成且已成功应用于提醒信息,因为您未在部分视图中显示任何其他详细信息。

 $(document).on('submit', '#applyForm', function () {
    var $theForm = $(this);
    // manually trigger validation
    if ($theForm.valid()) {
        $('#progress').show();
        $.post('', $theForm.serialize())
            .done(function (response) {
                $theForm.replaceWith(response);
            })
   bootbox.alert({
title: '<h4 style="color:white">Alert</h4>',
message: '<p  style="font-weight:700;">successfully applied</p>'
});

    }
    return false;
});

您可以参考此http://bootboxjs.com/链接

获取参考资料

答案 1 :(得分:-2)

删除条件if ($theForm.valid())后,它可以正常工作。编译时没有以某种方式定义方法valid()