2014-09-18 92 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