【发布时间】:2017-09-01 00:31:48
【问题描述】:
我有部分视图 LeftBanner.cshtml 应该显示来自数据库(图像)的一些数据
LeftBanner.cshtml
@model IEnumerable<WebApplication1.ViewModels.Banner>
<table class="table">
<tr>
<th>Test Banner!</th>
</tr>
@foreach (var banner in Model)
{
<tr>
<td>
@Html.LabelFor(b => banner.ImageDesc);
<img src="@Url.Content(banner.ImagePath)" alt="Image" />
</td>
</tr>
}
</table>
共享控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.ViewModels;
namespace WebApplication1.Controllers
{
public class SharedController : Controller
{
public ActionResult LeftBanner()
{
List<Banner> b = new List<Banner>() {
new Banner() {ImageDesc = "Left Banner Description", ImagePath = "~/Images/money.jpg" },
new Banner() {ImageDesc = "Left Banner Description2", ImagePath = "~/Images/money.jpg" }
};
return View(b);
// return View();
}
}
}
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
@RenderPage("~/Views/Shared/LeftBanner.cshtml")
</div>
</body>
</html>
错误
The model item passed into the dictionary is of type 'WebApplication1.ViewModels.EmployeeListViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[WebApplication1.ViewModels.Banner]'.
在 Asp.net Web-forms ascx 中,用户控件可以是独立的并且真正可重用。
请帮助我理解,为什么我不能封装我的部分视图? 这不是真正的重用, 如果我每次使用它时都必须传递给局部视图模型。 能不能独立,不传模型就去数据库?
非常感谢!
【问题讨论】:
-
将此添加到您的布局页面顶部@model WebApplication1.ViewModels
-
您好,我将@model WebApplication1.ViewModels.Banner 添加到布局页面。现在我得到另一个错误:传递到字典中的模型项的类型是“WebApplication1.ViewModels.EmployeeListViewModel”,但是这个字典需要一个类型为“WebApplication1.ViewModels.Banner”的模型项。
-
查看我下面的答案并告诉我。