mardi 11 août 2015

MVC Change ViewName on the fly

I have a project where i want to show different views to Desktop e Mobile users, mostly for better experience and speed. Right now i'm using 51degrees to tell me if the request comes from a mobile or desktop user and then in my Action Filter i will change the view name from "Index" to "Index.Mobile", the thing is i'm getting some problems with Views where i don't want to use a Layout at all.

This is my Method:

public override void OnActionExecuted( ActionExecutedContext filterContext )
    var result   = filterContext.Result as ViewResult;
    var view     = filterContext.ActionDescriptor.ActionName;

    //IsMobile is filled on my OnActionExecuting method
    var IsMobile = filterContext.Controller.ViewBag.IsMobile;

    if( result == null ) return;

    string viewName;
    string masterName;

    if( IsMobile )
        viewName   = view + ".Mobile";
        masterName = "_Layout.Mobile";

        //Check if view exists
        var viewResult = ViewEngines.Engines.FindView( filterContext.Controller.ControllerContext, viewName, null );

        if( viewResult.View == null )
            viewName = view;
        viewName   = view;
        masterName = "_Layout";

    result.ViewName   = viewName;
    result.MasterName = masterName;

What happens is, here i set a value for the MasterName or Layout and at two specific Controllers i need to set it as null but it still fetches the Layout i set before.

What i need is, this method will set the view and layout name and if needed i will set the Layout as null inside the view i loaded.

Can that be done ?

Aucun commentaire:

Enregistrer un commentaire