2011-07-01 101 views
6

我有一个局部视图和int它,没有从任何布局的任何继承的痕迹。但是,无论何时我想在视图中使用它(渲染它),布局都会重复一次以获取视图,并且一次获取部分视图。 This post建议创建一个空的布局。但我认为这是解决方法。无论如何停止加载部分视图的布局(主布局)。我不明白,为什么当没有代码使用主布局,为什么它应该被加载。这就像在ASP.NET中创建页面一样,并且看到它从主页面继承而没有<%@ Master ...指令。部分视图继承自主布局

这是我的部分观点:

@* Recursive category rendering *@ 
@using Backend.Models; 

@{ 
    List<Category> categories = new ThoughtResultsEntities().Categories.ToList(); 
    int level = 1; 
} 

@RenderCategoriesDropDown(categories, level) 

@helper RenderCategoriesDropDown(List<Category> categories, int level) 
{ 
    List<Category> rootCategories = categories.Where(c => c.ParentId == null).ToList(); 
    <select id='categoriesList' name='categoriesList'> 
    @foreach (Category rootCategory in rootCategories) 
    { 
     <option value='@rootCategory.Id' class='level-1'>@rootCategory.Title</option> 
     @RenderChildCategories(categories, level, rootCategory.Id); 
    } 
    </select> 
} 

@helper RenderChildCategories(List<Category> categories, int level, int parentCategoryId) 
{ 
    string padding = string.Empty; 
    level++; 
    List<Category> childCategories = categories.Where(c => c.ParentId == parentCategoryId).ToList(); 
    foreach (Category childCategory in childCategories) 
    { 
      <option value='@childCategory.Id' class='[email protected]'>@padding.PadRight(level, '-') @childCategory.Title</option> 
      @RenderChildCategories(categories, level, childCategory.Id); 
    } 
    level--; 
} 
+0

可以显示您的部分页面的第一行以及您的控制器操作方法,从而覆盖了此行为? –

回答

13

在通过ajax cal渲染部分页面时,我能够重现此问题LS。

return View("partialpage") 

总会伴随布局。我通过明确调用

return PartialView("partialpage") 
+0

好习惯。我不知道PartialView是ActionResult类型之一。但是当你不使用ajax时你会做什么,并且你想基于将某些部分视图(如仪表板)放在一起来构建页面。哪种方法? –

+1

根据模型的可用性,我使用RenderPartial或RenderAction –

9

布局可能与您的~/Views/_ViewStart.cshtml

@{ 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

是未来你可以尝试在你的局部视图重写此类似:

@{ 
    Layout = null; 
} 
+0

这对我有用。谢谢。但这不是很奇怪吗?在WebForms中,它总是说“这个页面没有母版页”,或者“这个用户控件没有母版页”。我的意思是,似乎默认值应该是'Layout = null;'并且不应该有必要明确地说出来。 –

+0

WebForms视图引擎使用不同的文件扩展名(.ascx表示部分,.aspx表示页面)。另一方面,剃须刀对所有东西都使用相同的扩展名,所以这可能是原因(尽管如此,并非100%确定)。顺便说一句,我不能重现你的问题。你怎么称呼你的部分?我试着@ Html.Partial(“_ Foo”),它只是工作。无需将布局设置为空。 –

+1

我用'@ Html.Action(“PartialViewControllerAction”)'。方法文档说它返回部分视图执行的渲染结果。 –