MVC PartialViewResult 直接和来自其他 ActionResult

MVC PartialViewResult direct and from other ActionResult

我的 MVC 中有一个 PartialViewResult。 如果我直接在浏览器中打开它,我就会从我的模型中获得数据。如果我在其他视图中打开它,我没有数据。你能告诉我为什么吗?

控制器文件:

public PartialViewResult PartialData() {
  return PartialView(dataTable);
}

CSHTML 文件:

@model System.Data.DataTable
@using System.Data;

@this.Model.Columns[0]

从另一个 CSHTML 调用

@Html.Partial("RunningJobs")

这一行的错误:@this.Model.Columns[0]

The object reference has not been set to an object instance.

当您从浏览器打开它时,意味着您正在点击已经传递模型(即数据表)的 "PartialData" 操作。 但是,当您从另一个 CSHTML 加载局部视图时,您没有传递任何模型并且它为空。尝试在主视图中使用 @Html.RenderAction 而不是使用 @Html.Partial.

我认为以下内容应该对您有所帮助 -

@Html.RenderAction("PartialData")

当在父视图中调用部分视图时,您必须将模型传递给父视图

public ActionResult ShowParentView() {
  return view(dataTable);
  }