ASP MVC尝试从字符串模型加载布局

时间:2014-09-18 17:22:45

标签: asp.net-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

1 个答案:

答案 0 :(得分:4)

这是因为View()函数的重载。如果只传递一个字符串,它会认为你要告诉它要加载的视图的实际名称,而不是传递一个类型为string的简单模型。

例如,View()函数无法区分:

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.强烈键入视图的名称,并作为第二个参数传递布局字符串

<强>控制器

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";
}