MVC2到MV4的转换错误

时间:2014-01-28 10:53:37

标签: asp.net-mvc

我在MVC2中有一个项目,我已将其转换为MVC3然后我将其转换为MVC4,我已使用this工具将aspx视图转换为Razor Views, 在转换我的应用程序编译成功后,我也安装了MVC3和MVC4但是当我运行应用程序时显示错误

  

无法转换“Microsoft.Web.Mvc.FixedRazorViewEngine”类型的对象   输入'System.Web.Mvc.WebFormViewEngine'。

在Global.asax

private static void AddViewPaths()
{
    foreach (var engine in ViewEngines.Engines)
    {              
        ((WebFormViewEngine)engine).PartialViewLocationFormats =
            ((WebFormViewEngine)engine).PartialViewLocationFormats.Union(
            new string[] { "~/Views/Sample/{0}.aspx", "~/Views/Sample/{0}.ascx" }).ToArray();

          ((WebFormViewEngine)engine).ViewLocationFormats =
              ((WebFormViewEngine)engine).ViewLocationFormats.Union(
              new string[] { "~/Views/Sample/{0}.aspx", "~/Views/Sample/{0}.ascx" }).ToArray();
      }
}

我尝试将这些行更改为此,但仍然存在同样的问题,我该怎么办?

 ((WebFormViewEngine)engine).PartialViewLocationFormats =
        ((WebFormViewEngine)engine).PartialViewLocationFormats.Union(
        new string[] { "~/Views/Sample/{0}.cshtml", "~/Views/Sample/{0}.cshtml" }).ToArray();

  ((WebFormViewEngine)engine).ViewLocationFormats =
        ((WebFormViewEngine)engine).ViewLocationFormats.Union(
        new string[] { "~/Views/Sample/{0}.cshtml", "~/Views/Sample/{0}.cshtml" }).ToArray();

问题是我在ViewEngines.Engines集合中同时拥有Razor和WebForms,我怎样才能获得Razor Views

1 个答案:

答案 0 :(得分:1)

由于您已移至剃刀(MVC 2中未提供),因此您现在拥有的不仅仅是for循环中可用的WebFormsViewEngine。你的代码,现在写的,它试图将Razor引擎转换为WebForms引擎,这是无法完成的。如果您更新硬铸件并移除所有其他引擎,它应该可以工作,您可以摆脱for循环 - 您的集合中只有一个引擎。

<强>的Application_Start

//clear all but RazorViewEngine
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());

现在您更新的代码只是

  var engine = ViewEngines.Engines.First();
  ((RazorViewEngine)engine).PartialViewLocationFormats =
    ((RazorViewEngine)engine).PartialViewLocationFormats.Union(
     new string[] { "~/Views/Sample/{0}.cshtml", "~/Views/Sample/{0}.cshtml" }).ToArray();

  ((RazorViewEngine)engine).ViewLocationFormats =
    ((RazorViewEngine)engine).ViewLocationFormats.Union(
     new string[] { "~/Views/Sample/{0}.cshtml", "~/Views/Sample/{0}.cshtml" }).ToArray();

如果您决定不删除所有引擎,那么您将不得不在for循环中执行if/else以确定转发引擎的方式。