ASP.NET MVC 使用列表的局部视图

5

我正在进行我的第一个MVC项目。我想创建一个带有标题的页面,并在此标题中放置一个分类列表的部分视图。

到目前为止,我已经完成了以下工作: 我创建了主页面(_Home.cshtml)。然后在Shared文件夹中创建了一个视图(Category.cshtml)。请参见我的图片。 enter image description here

我的Category.cshtml内容:

@model IEnumerable<ArtSchool.Models.Category>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Visible)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Visible)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Details", "Details", new { id=item.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
</tr>

我的主页文件:

主页文件是指:

@{
Layout = null;
}

<!DOCTYPE html>

 <html>
 <head>
<meta name="viewport" content="width=device-width" />
<title>_Home</title>
</head>
<body>
<div>

    @Html.Partial("ASCX/Header")

    @Html.Partial("Category")

    @RenderBody()
</div>

当我运行项目时,出现了错误:enter image description here。 我知道这是一个初学者的问题,但这是我的第一个MVC项目。谢谢!

您需要在调用 @Html.Partial("Category") 时传递一个 Model。您应该调用一个控制器/操作,以生成此模型,然后返回部分视图。 - Andrei V
你在你的操作中做了什么??你应该在你的控制器中呈现部分视图。 - Ehsan
你确定吗?在我的项目中,我没有展示更多的东西。我没有传递任何额外的数据,调用控制器,返回部分,一切都正常。 - szpic
@szpic,你的部分视图是强类型的吗?如果是,那么对“Model”的任何引用都会产生相同的错误。 - Andrei V
@AndreiV 是的,在我的vs中强类型是默认选项。没有创建强类型等复选框。 - szpic
2个回答

7

解决方案 1

如果您想使用局部视图,需要通过以下方式将模型传递给该帮助程序:

@Html.Partial("Category", CategoryModel)

在通过此模型之前,您需要使用一些数据填充它。

解决方案2

您还可以使用@Html.Action()方法,并使用ActionResult方法的名称,该方法将为您返回部分视图。

例如:

  @Html.Action("GetCategories", "ControllerName")

  public ActionResult GetCategories() {
    // fill some data for your model here
    return PartialView("Category", model);
  }

2
如果您想将这些 partial 视为 HTML 中的某些静态部分,则建议您调用 Html.Action(),该方法将返回您的 partials:
@Html.Action("GetPageHeader","Home")
@Html.Action("GetPageCategories","Home")

HomeController

[HttpGet]
public ActionResult GetPageHeader()
{
   return PartialView(@"~/Views/Shared/_PageHeader.cshtml");
}

[HttpGet]
public ActionResult GetPageCategories()
{
   var categories = databaseContext.GetAllCategories(); //Get your categs
   return PartialView(@"~/Views/Shared/_Categories.cshtml",categories);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接