2011-11-28 75 views
2

我正在创建一个面包屑部分视图,它包含标题/ URL的集合。该集合将在操作方法中生成,并且必须在面包屑部分视图中可用。如何在mvc 3中跨视图和部分视图传递变量?

我试图把它做对夫妇的方式,这是在这样的一个:http://goo.gl/rMFlp

但一些如何我无法得到它的工作。我得到的只是一个“未设置为对象实例的对象引用”。你们能帮我吗?

{Updare} 下面是代码:

我创建的模型类,如下所示

public class ShopModel 
{ 
    public Dictionary<string,string> Breadcrumb { get; set; } 
} 

处理法

public ActionResult Index() 
    { 
     var breadcrumbCollection = new Dictionary<string,string>(); 
     breadcrumbCollection.Add("/home","Home"); 
     breadcrumbCollection.Add("/shop","Shop"); 

     var model = new ShopModel() { Breadcrumb = breadcrumbCollection}; 

     return View(model); 
    } 

模型结合视图 - 索引

@Model NexCart.Model.Model.Custom.ShopModel 

最后这里是局部视图代码:

<div> 
@{ 
    foreach (var item in @Model.Breadcrumb) 
    { 
     <a href="#">@item.Key</a> 
    } 
    } 

+3

请张贴您的代码。 – Maess

回答

1

您还没有表现出任何代码,所以你的问题是不可能的回答。这就是说你可以继续下去。一如往常,在ASP.NET MVC应用程序,你首先来定义视图模型:

public class Breadcrumb 
{ 
    public string Title { get; set; } 
    public string Url { get; set; } 
} 

,那么你可以写一个控制器的动作,将填充的面包屑集合,并将它们传递到局部视图:

public class BreadcrumbController: Controller 
{ 
    public ActionResult Index() 
    { 
     // TODO: pull the breadcrumbs from somewhere instead of hardcoding them 
     var model = new[] 
     { 
      new Breadcrumb { Title = "Google", Url = "http://www.google.com/" }, 
      new Breadcrumb { Title = "Yahoo", Url = "http://www.yahoo.com/" }, 
      new Breadcrumb { Title = "Bing", Url = "http://www.bing.com/" }, 
     }; 
     return PartialView(model); 
    } 
} 

然后,你可以有这会使这模型(~/Views/Breadcrumb/Index.cshtml)对应的局部视图:

@model IEnumerable<Breadcrumb> 
<ul> 
    @Html.DisplayForModel() 
</ul> 

和相应的显示模板( ~/Views/Breadcrumb/DisplayTemplates/Breadcrumb.cshtml):

@model Breadcrumb 
<li> 
    <a href="@Model.Url">@Model.Title</a> 
</li> 

现在,所有剩下的就是包括这个孩子的动作使用Html.Action helper地方。例如,如果重复每一页上这个面包屑,你可以在_layout做到这一点:

@Html.Action("Index", "Breadcrumb") 

但很明显,它也可以在任何视图来完成。

+0

感谢@Darin,我想知道在这种情况下使用的一般模式。不过,我迟迟没有发布我的代码。感谢您的帮助.. :) – Amit

+0

我得到它的工作......谢谢.. :) – Amit