0
votes

I created a layout view in a separate project (let's call it Shared) from the main MVC project (let's call it Main) and compiled that view using RazorGenerator. When I use the layout in any MVC page in Main it works fine:

@{
   Layout = "~/Views/Shared/_Layout.cshtml";
}

However, when I set the layout using an ActionFilter this way:

public class LayoutAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var viewResult = filterContext.Result as ViewResult;
        viewResult.MasterName = "~/Views/Shared/_Layout.cshtml";
    }
}

And simply use it in the controller in Main like this:

[Layout]
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}

I get this error:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/Home/Index.cshtml ~/Views/Shared/Index.cshtml ~/Views/Home/Index.aspx ~/Views/Home/Index.ascx ~/Views/Shared/Index.aspx ~/Views/Shared/Index.ascx ~/Views/Shared/_Layout.cshtml

I'd really like to use an ActionFilter built into the Shared project so that I can just use it in any controller in the Main project (or any others).

Any ideas why I'm getting this error?

1
@jamiedanq It is there. Like I said, when I use the Layout = "..." directly from the Index view it works. When I remove that line and use the ActionFilter instead I get the error.System Down
Missed that part my wrongjamiedanq
Does the LayoutAttribute class reside in the same project as the Layoutjamiedanq
@jamiedanq Yes. Although I've tried having the class as part of the Main project and I still got the same issue.System Down

1 Answers

0
votes

Change your action from this:

public class LayoutAttribute : ActionFilterAttribute

    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            var viewResult = filterContext.Result as ViewResult;
            viewResult.MasterName = "~/Views/Shared/_Layout.cshtml";
        }
    }

To this one below:

public class LayoutAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var viewResult = filterContext.Result as ViewResult;
        if (viewResult != null)
        {
             viewResult.MasterName = "~/Views/Shared/_Layout.cshtml";
         }
    }
}

Hope that helps.