【问题标题】:How to load another view as PartialView when the current View loads?当前视图加载时如何将另一个视图加载为 PartialView?
【发布时间】:2018-09-05 00:21:41
【问题描述】:

我对此比较陌生。我正在处理这个ASP.NET Core MVC 项目,当Main ViewLocate.cshtml 加载时,我想在当前Main View 中的<div> 中加载PartialViewHistoryTable.cshtml。换句话说,我希望PartialViewMainView 加载/重新加载时出现。

我正在通过以下方式实现它:

Locate.cshtml

@model Project.Models.CustomModels.LocationsHistoryViewModel
<div class="container">
...
    <div id="divLocationsHistoryTable"></div>
...
</div>

@section Scripts {
<script type="text/javascript">

    $(document).ready(function () {
        $(".disabledropdowncntrl").prop('disabled', false).trigger("chosen:updated");
        $("#divLocationsHistoryTable").load("/Project/HistoryTable");
    });

HistoryTable.cshtml

@model IEnumerable<Project.Models.CustomModels.LocationsHistoryViewModel>
<div class="card">
...
@if(Model.Count() != 0)
{
    <thead>
        <tr>
            <th data-column-id="UserId" data-type="string" data-identifier="true" hidden>User ID</th>
            <th data-column-id="Name">Name</th>
            ...
        </tr>
    </thead>

}
else
{
    ...
}
<tbody>
    @foreach(var item in Model)
    {
        <tr>
            <td>
                @item.User.FirstName @item.User.LastName
            </td>
            ...
        </tr>
    }
</tbody>
</div>

控制器:定位 ActionMethod

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Locate(int Id, InventoryLocationsHistoryViewModel locationsHistoryVM)
{
    ...
    var HistoryObject = _context.History
        .Include(...
        .Where(...
        .Select(...
    {
        ...
    }).ToList();

    return PartialView("/Project/HistoryTable", HistoryObject);
}

怎么办?

编辑

我面临的问题类似于this question,但不同的是我必须在这里使用Submit 按钮,因为我在这里提交formSubmit 按钮在点击时必须做两件事:

  1. form 详细信息保存到数据库中。
  2. 更新必须始终显示在Submit 按钮下方的HistoryTable。这个HistoryTable 必须始终显示(甚至在单击Submit 之前)。因此,我不能使用Button

【问题讨论】:

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


【解决方案1】:

这里有很多问题,让你很难弄清楚你真正想要实现的目标。

首先,您的Locate 操作应该在GET 和POST 上返回您的Locate.cshtml 视图。该视图包含您的HistoryTable.cshtml 部分视图这一事实是一个实现细节。如果您只在 POST 上返回部分内容,则浏览器中将只有部分 HTML,而不是完整的 Locate 视图。

然后,您似乎正在尝试使用 jQuery 的 load 方法来加载您的实际部分,而不是返回该部分的操作。您无法直接获得视图;您需要提交一个 AJAX 请求(load 正在做什么)到与返回该部分的操作绑定的 路由

接下来,您的部分似乎需要一个有效负载,即需要“发布”一些对象才能使用它。如果是这种情况,您需要将需要发布的内容的 JavaScript 对象表示传递给 load 方法作为其第二个参数。事实上,它只是直接发出一个 GET 请求,不传递任何数据。

但是,由于您只是在页面加载时执行此操作,因此您会质疑您为什么要使用 AJAX。只有在页面加载后稍后需要更改某些内容时,AJAX 才有意义。如果您在加载时执行 AJAX 请求,则应该从一开始就将其内置到页面中,从而无需单独的请求。

最后,当您将模型包含在页面中时,您可以将模型传递给局部视图,但您在此处实际寻找的很可能是view component,即能够实际执行诸如查询之类的逻辑的东西来自数据库,与正在运行的主请求分开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多