在 Razor Pages 上不显眼 ajax post 后更新局部视图

update Partial View after unobtrusive ajax post on Razor Pages

我有一个父视图并在其中渲染了局部视图。我在部分视图中添加了表单标签。它转到控制器和 return 数据,但部分视图内容不会更新。

<div class="row main-section-border">
        <div class="col-sm-12">

            @{
                await Html.RenderPartialAsync("_Partial", Model);
            }
        </div>
        </div>

局部视图

    @model RandomModel 
    <form asp-controller="Controller" asp-action="Save" method="POST" data-ajax="true" data-ajax-success="success" data-ajax-failure="failed" data-ajax-update="#spForm">

    <div class="row left-right-padding" id="spForm">
        <input type="text"  id="document" asp-for="Document">
</div>

后端:

  public IActionResult Save(Random Model model)
        
     {     model.Document= "Random"
            return PartialView("~/Views/RandomFolder/_Partial.cshtml", model);
      }

return PartialView("~/Views/RandomFolder/_Partial.cshtml", model);

由于你使用了unobtrusive ajax,所以它会return局部视图的html代码,但不会刷新你要刷新的局部view.If部分视图,您可以尝试用 data-ajax-complete 替换 html 代码。这是一个工作演示:

div class="row main-section-border">
        <div id="div1" class="col-sm-12">

            @{
                await Html.RenderPartialAsync("_Partial", Model);
            }
        </div>
        </div>
@section scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js"></script>
    <script>
        completed = function (xhr) {
            $("#div1").html(xhr.responseText);
        };
    </script>
}

局部视图:

@model RandomModel 
    <form asp-controller="Controller" asp-action="Save" method="POST" data-ajax="true" data-ajax-success="success" data-ajax-failure="failed" data-ajax-update="#spForm" data-ajax-complete="completed">

    <div class="row left-right-padding" id="spForm">
        <input type="text"  id="document" asp-for="Document">
</div>

后端(您需要使用 ModelState.Clear(); 否则它将更愿意使用 ModelState 中的模型值而不是您传递给分部视图的模型。):

public IActionResult Save(RandomModel model)

        {
            ModelState.Clear();
            model.Document = "Random";
            return PartialView("~/Views/B/_Partial.cshtml", model);
        }

结果: