【问题标题】:update Partial View after unobtrusive ajax post on Razor Pages在 Razor 页面上不显眼的 ajax 发布后更新部分视图
【发布时间】:2021-11-16 12:53:09
【问题描述】:

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

<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);
      }

【问题讨论】:

    标签: jquery asp.net asp.net-core asp.net-core-mvc razor-pages


    【解决方案1】:

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

    由于你使用unobtrusive ajax,所以它会返回局部视图的html代码,但不会刷新局部视图。如果要刷新局部视图,可以尝试将html代码替换为@ 987654324@.这是一个工作演示:

    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中的模型值而不是你传递给Partial视图的模型。):

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

    结果:

    【讨论】:

    • 您能接受它作为答案吗?谢谢。
    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 2020-11-26
    • 2020-12-24
    • 2020-10-10
    • 2019-06-28
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多