Asp.net-Mvc

部分視圖繼承自主佈局

  • July 1, 2011

我有一個局部視圖和 int 它,沒有任何佈局的任何繼承痕跡。但是每當我想在視圖中使用它(渲染它)時,佈局會為視圖重複一次,為局部視圖重複一次。這篇文章建議創建一個空佈局。但我認為這是解決方法。無論如何要停止載入部分視圖的佈局(主佈局)。我不明白,為什麼當沒有使用主佈局的程式碼時,為什麼要載入它。這就像在 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='level-@level'>@padding.PadRight(level, '-') @childCategory.Title</option>
         @RenderChildCategories(categories, level, childCategory.Id);
    }
    level--;
}

通過 ajax 呼叫呈現部分頁面時,我能夠重現此問題。這

return View("partialpage")   

總是伴隨著佈局。我通過顯式呼叫覆蓋了這種行為

return PartialView("partialpage")  

佈局可能來自您的~/Views/_ViewStart.cshtml

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

您可以嘗試在部分視圖中覆蓋它,例如:

@{
   Layout = null;
}

引用自:https://stackoverflow.com/questions/6546517