gpt4 book ai didi

c# - MVC 局部 View

转载 作者:行者123 更新时间:2023-11-30 15:01:09 25 4
gpt4 key购买 nike

我正在尝试重用一些代码,部分 View 似乎是使用 MVC 时执行此操作的最佳方式。

我创建了一个继承自 IEnumerable 的局部 View (见下文)。

@model IEnumerable<Models.facility>

<div class="display-field">
@foreach (var facility in Model)
{
<li>
@facility.name
</li>
}
</div>

嵌入这个 View 的 View 是这样的:

<div class="display-field">
<div> @{Html.RenderPartial("FacilityPartial");} </div>
</div>

那么问题来了。

我收到空引用错误,我可以看到 Model 变量为空。

错误:

Object reference not set to an instance of an object.

有人可以告诉我我是否在做正确的事情以及我哪里出错了,除了它是 null 的事实之外?

最佳答案

使用 Html.Partial。考虑这个例子。

索引 View (主页)

 @{
ViewBag.Title = "Home Page";
//Test model to be passed to the partial view
var products = new List<Product> { new Product{ProductName="Test product 1", ProductId=1234}};
}
@Html.Partial("_TestPV", products)

_TestPV(局部 View )

@model IEnumerable<Product>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
ProductName
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ProductName)
</td>
</tr>
}
</table>

输出:

enter image description here

关于c# - MVC 局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14642401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com