我正在关注Pro ASP.NET MVC 2 Framework中构建的示例网站(但在我使用时使用Razor而不是ASPX)。
然而,我遇到了局部观点。我收到以下错误:
The model item passed into the dictionary is of type
'SportsStore.WebUI.Models.ProductsListViewModel', but this dictionary requires a model
item of type 'System.Collections.Generic.IEnumerable`1[SportsStore.WebUI.Models.NavLink]'.
以下是相关文件:
_Layout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link rel="stylesheet" href="@Url.Content("~/Content/global.css")" />
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"><script>
</head>
<body>
<header>
<h1>SPORTS STORE</h1>
</header>
<nav class="categories">
@{ Html.RenderAction("Menu", "Nav"); } // <!-- HERE IS THE PROBLEM -->
</nav>
<section id="content">
@RenderBody()
</section>
</body>
</html>
Menu.cshtml (部分视图):
@model IEnumerable<SportsStore.WebUI.Models.NavLink>
@foreach (var link in Model)
{
@Html.RouteLink(link.Text, link.RouteValues);
}
NavController.cs:
namespace SportsStore.WebUI.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
using SportsStore.WebUI.Models;
public class NavController : Controller
{
private IProductsRepository productsRepository;
public NavController(IProductsRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult Menu()
{
Func<string, NavLink> makeLink = categoryName => new NavLink
{
Text = categoryName ?? "Home",
RouteValues = new System.Web.Routing.RouteValueDictionary(
new
{
controller = "Products",
action = "List",
category = categoryName,
page = 1
})
};
List<NavLink> navLinks = new List<NavLink>
{
makeLink(null)
};
var categories = productsRepository.Products.Select(x => x.Category);
foreach(var categoryName in categories.Distinct().OrderBy(x => x))
navLinks.Add(makeLink(categoryName));
return View(navLinks);
}
}
}
NavLink.cs (View-Model类):
namespace SportsStore.WebUI.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
public class NavLink
{
public string Text { get; set; }
public RouteValueDictionary RouteValues { get; set; }
}
}
修改 当我使用ASCX部分视图而不是剃刀局部视图时,以下工作正常:
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<SportsStore.WebUI.Models.NavLink>>" %>
<% foreach (var link in Model) { %>
<%: Html.RouteLink(link.Text, link.RouteValues)%>
<% } %>
答案 0 :(得分:1)
您希望使用RenderAction而不是RenderPartial,因为RenderPartial会为您当前正在加载的任何其他视图制作当前模型的副本,并将其发送到您的视图(并且永远不会执行您的控制器方法)。 IE RenderPartial不会调用您的方法..只有您的视图。 RenderAction将调用您的控制器方法,然后调用局部视图。
在您的视图中使用:
@Html.Action("Menu", "Nav")
您的路线很简单(假设是一般导航栏,没有参数)
routes.MapRoute( "NavMenu", // Route name "Nav/Menu", // URL with parameters new { controller = "Nav", action = "Menu"} );
答案 1 :(得分:1)
尝试更新控制器中的Menu功能以返回PartialView
public PartialViewResult Menu()
{
.
.
return PartialView(NavLinks)
}