【问题标题】:How use asp.net mvc partial view in layout within @RenderPage [duplicate]如何在@RenderPage [重复] 中的布局中使用 asp.net mvc 部分视图
【发布时间】: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”的模型项。
  • 查看我下面的答案并告诉我。

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

在你的 LeftBanner() Action 方法中return 像这样,

return PartialView("LeftBanner",b);

然后在您的 _Layout.cshtml 页面中,像下面这样调用操作 LeftBanner

@Html.Action("LeftBanner", "Shared")

希望对你有帮助:)

【讨论】:

  • 非常感谢!它适用于@Html.Action("LeftBanner", "Shared") 我如何在@RenderPage 中使用部分视图?有可能吗?
  • 很高兴它对您有所帮助。请标记为答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多