how can i set layout to null in action filter?

2019-06-07 16:10发布

问题:

Is it posible to set the layout to null in action filter? For example

public ActionResult SomeAction()
    {
        return PartialView();
    }

I want to render some action with

@Html.Action("someaction")

it works for now.

But i want to use this action in 2 modes : like child and like master for different situations. I can set Layout to null in view for this

view:

@{
   if(condtition)
   {
        Layout = null;
   }
}

But i want to find more elegant way :)

Like:

action without partial

public ActionResult SomeAction()
        {
            return View();
        }

and in filter set the layout to null if action is child

 public class LayoutFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
           if(filterContext.IsChildAction)
           {
               //set the layout to NULL here!

           }
        }
    }

It is posible? Any ideas?

回答1:

In your example you have overriden the OnActionExecuting event but this happens way too early. The actions hasn't even executed yet nor returned an ActionResult and you are already attempting to set its Layout.

Wait for it to complete, by overriding the OnActionExecuted event, retrieve the Result property from the filterContext and if it is a ViewResult set its MasterName property to null:

public class LayoutFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = null;
        }
    }
}