ASP.NET Core MVC 显示隐藏部分视图

ASP.NET Core MVC Show hide partial views

我有一个 Contact/Index 页面分为两列(每列一个 PartialView)。在左侧,我显示了我所有联系人的列表,在右侧显示了上述列表中 selected/clicked 联系人的详细信息。

...并且预览效果很好 -> 在用户单击列表中的记录后,我只是调用 '@Url.Action' 在我的控制器中执行 returns 部分操作查看详细信息。


    <div class="row">
      <div class="col-md-8 col-sm-12">
        <div id="sectionList">
          @{await Html.RenderPartialAsync("_PartialList", Model.Contacts);}
        </div>
      </div>

      <div class="col-md-4 col-sm-12">
        <div id="sectionPreview" style="display: block">
          @{await Html.RenderPartialAsync("_PartialPreview", Model.Contact);}
        </div>

        <div id="sectionEdit" style="display: none">
          @{await Html.RenderPartialAsync("_PartialEdit", Model.Contact);}
        </div>
      </div>
    </div>

但是 'edit' 我遇到了问题。在详细信息表单上,我有一个用于编辑的按钮,当用户单击它时,我想隐藏 PartialView 以供预览 (id="sectionPreview") 并显示用于编辑的部分 (id="sectionEdit")。

我已经尝试过将不同的样式(显示:块或 none)保存到 ViewBag 并将其应用于每个部分,但感觉这不是正确的方法,因为所有的 PartialViews (即使显示设置为 none) 仍然会被渲染。

使这项工作最好的 way/practice 是什么?

另一种方法是使用 ajax 加载局部视图。在客户端使用 ajax 调用服务器端函数并传递过滤器参数(id)。在服务器端,您可以使用 ID 和 return 带有模型的 PartialView 查询数据库。

然后在Ajax的成功回调函数中,可以使用jQuery将局部视图的html加载到页面相关区域:

success: function (result) {
    $("#searchResultsGrid").html(result);
}

并隐藏相关的 div 如:

$("#sectionPreview").hide();

您可以点击 here 查看代码示例。