Search code examples
c#asp.net-mvcasync-awaitt4mvc

Is it possible to use T4MVC and Asynchronous operations?


My Action:

 public virtual async Task<ActionResult> IdeaDetails(int id)
        {

My routes:

 routes.MapRoute("DesignIdeasDetails", "ideadetails/{id}",
              MVC.Designer.IdeaDetails().AddRouteValue("id", UrlParameter.Optional)

Error: Instance argument: cannot convert from 'System.Threading.Tasks.Task<System.Web.Mvc.ActionResult>' to 'System.Web.Mvc.ActionResult' C:\Work\luxedecorNew\Luxedecor\Luxedecor\App_Start\RouteConfig.cs 19 15 Luxedecor

Error 2: System.Threading.Tasks.Task<System.Web.Mvc.ActionResult>' does not contain a definition for 'AddRouteValue' and the best extension method overload 'System.Web.Mvc.T4Extensions.AddRouteValue(System.Web.Mvc.ActionResult, string, object)' has some invalid arguments


Solution

  • The errors occur because of how async works. You need to await the Task in your method so that you can get the ActionResult, like this:

    routes.MapRoute("DesignIdeasDetails", "ideadetails/{id}",
              (await MVC.Designer.IdeaDetails()).AddRouteValue("id", UrlParameter.Optional)
    
    // or, if the method cannot be used with async/await
     routes.MapRoute("DesignIdeasDetails", "ideadetails/{id}",
              (MVC.Designer.IdeaDetails().GetAwaiter().GetResult()).AddRouteValue("id", UrlParameter.Optional)