2014-09-18 91 views
3

我想加載一個簡單的觀點ASP MVC試圖

@model string 
@{ 
    ViewBag.Title = "TestPage"; 
    Layout = "~/Views/Shared/" + Model + ".cshtml"; 
} 
<style> 
    body { 
     background-color: black; 
    } 
</style> 
<h2>Page_Import</h2> 

從弦模型加載佈局,因爲你很可能會看到,我試圖從控制器通過佈局頁面的名稱,

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace mvcRockslide03.Controllers 
{ 
    public class HomeController : Controller 
    { 
     // 
     // GET: /Home/ 

     public ActionResult Index() 
     { 
      return View(); 
     } 

     public ActionResult TestImport() 
     { 
      return View("_Layout"); 
     } 
    } 
} 

,但是當我打開網頁,我得到以下錯誤:

Server Error in '/' Application. 

The file "~/Views/Shared/Forum_Layout.cshtml" cannot be requested directly because it calls the "RenderSection" method. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Web.HttpException: The file "~/Views/Shared/Forum_Layout.cshtml" cannot be requested directly because it calls the "RenderSection" method. 

Source Error: 


Line 8: <body> 
Line 9:  <div class="content-wrapper">   
Line 10:   @RenderSection("featured", required: false) 
Line 11:   <section class="content-wrapper main-content clear-fix"> 
Line 12:   @RenderBody() 

Source File: f:\mvcRockslide03\mvcRockslide03\Views\Shared\Forum_Layout.cshtml Line: 10 

,但是當我改變

@model string 
@{ 
    Layout = "~/Views/Shared/" + Model + ".cshtml"; 
} 

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

視圖 和

public ActionResult TestImport() 
{ 
    return View("_Layout"); 
} 

public ActionResult TestImport() 
    { 
     return View(); 
    } 

在HomeController中, 它工作正常。

我真的很難過,任何幫助都將得到廣泛的讚賞。

感謝, JMiller

回答

4

這是因爲視圖()函數的重載。如果你只傳遞一個字符串,它認爲你告訴它要加載的視圖的實際名稱,而不是傳遞一個簡單的字符串模型。

例如,查看()函數不能區分之間:和

return View("~/Views/Home/myView.cshtml"); 

return View("_Layout"); 

周圍有這一點,我能想到的幾種方法。

1.使用ViewData []來保存佈局視圖的名稱。

控制器

public ActionResult TestImport() 
{ 
    ViewData["layout"] = "_Layout" 
    return View(); 
} 

查看

@{ 
    Layout = "~/Views/Shared/" + ViewData["layout"] + ".cshtml"; 
} 

2.Strongly鍵入視圖的名稱和作爲第二個參數,通過佈局串

控制器

public ActionResult TestImport() 
{ 
    return View("TestImport", "_Layout"); 
} 

3.創建一個具有字符串屬性的模型,並將其傳回給視圖。

模型類

public class LayoutModel{ 

    public string LayoutName {get;set;} 
} 

控制器

public ActionResult TestImport() 
{ 
    return View(new LayoutModel{LayoutName = "_Layout"}); 
} 

查看

@model LayoutModel 
@{ 
    Layout = "~/Views/Shared/" + Model.LayoutName + ".cshtml"; 
} 
+0

天哪,我覺得愚蠢,這真是棒極了! – jmiller3496 2014-09-18 17:39:20

+0

不,不難過。我認爲這已經讓我們所有的MVC開發者至少陷入了一次。 – Tommy 2014-09-18 18:01:37