使用T4MVC生成的代码在MVC 3项目中编译错误

Ser*_*rgi 5 asp.net-mvc t4mvc asp.net-mvc-3

我们正在使用ASP.Net 4和MVC 3 Framework开发Web应用程序.我已经通过NuGet安装了T4MVC,所有的视图,控制器和静态内容都成功地生成为强类型.

但是,当我尝试编译项目时,它会在生成的文件T4MVC.cs中引发错误,这是:

'T4MVC_ViewResultBase.FindView(System.Web.Mvc.ControllerContext)': 
 return type must be 'System.Web.Mvc.ViewEngineResult' to match overridden member
 'System.Web.Mvc.ViewResultBase.FindView(System.Web.Mvc.ControllerContext)'
Run Code Online (Sandbox Code Playgroud)

这是生成的源代码:

[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class T4MVC_ViewResultBase : System.Web.Mvc.ViewResultBase,
                                                            IT4MVCActionResult 
{
  public T4MVC_ViewResultBase(string area, string controller, string action):
      base()  {
       this.InitMVCT4Result(area, controller, action);
    }

    protected override void FindView(System.Web.Mvc.ControllerContext context){}

    public string Controller { get; set; }
    public string Action { get; set; }
    public RouteValueDictionary RouteValueDictionary { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

错误说:

protected override void FindView(System.Web.Mvc.ControllerContext context) { }
Run Code Online (Sandbox Code Playgroud)

应该:

protected override ViewEngineResult 
               FindView(System.Web.Mvc.ControllerContext context) { }
Run Code Online (Sandbox Code Playgroud)

但是它会引发另一个编译错误,因为这个方法应该返回代码.

如果我们检查它继承的基类System.Web.Mvc.ViewResultBase,它实际上使用ViewEngineResult返回类型声明FindView():

public abstract class ViewResultBase : ActionResult
    {
        ...
        protected abstract ViewEngineResult FindView(ControllerContext context);
    }
Run Code Online (Sandbox Code Playgroud)

有人有这个错误吗?它与MVC版本有关,我们是否正在使用MVC 3?

非常感谢!塞尔吉

Dav*_*bbo 5

我想我看到了问题,这是一个T4MVC错误.但希望它很容易解决.

您是否有声明返回ViewResultBase的控制器操作?如果是这样,您可以将返回类型更改为ActionResult吗?或者,您可以将返回类型更改为您要返回的具体类型(例如,是ViewResult)吗?

T4MVC错误是它没有正确覆盖ActionResult类型中的非void方法.

  • 是! 就是这样!我会问开发者为什么这个动作会返回"ViewResultBase".将它改为"ViewResult"就成了伎俩.我一直在研究T4MVC.tt模板,我在第333行找到了这个:`<#= method.IsPublic?"public":"protected"#>覆盖void <#= method.Name#>(<#method.WriteFormalParameters(true);#>){}`我可以看到_void_硬编码.我认为你的意思是_它没有正确地覆盖ActionResult types_中的非void方法.我试图修复它检查`method.ReturnType =="Void"`,但显然你需要返回一些东西...... (2认同)