tags:

views:

77

answers:

2

I trying to return a ViewResult in OnActionExecuted method override from ActionFilterAttribute class.Like below:

  public override void OnActionExecuted(ActionExecutedContext filterContext)
    {

        if (CreateCookie && filterContext.Exception == null)
        {
            LoginCookies lcookie = new LoginCookies(usuDs, usuSenha);
            lcookie.WriteCookie("SCE", 10);
        }
        else
        {
            filterContext.Result = new ViewResult() { ViewName = "Login" };
            filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
        }

It works fine to return to a view called "Login",but i need to pass the model object to this view (in this case model object is type of Users) and i dont know how to pass it using ViewResult class directly.

Any ideias?

UPDATED: Ive solved my problem setting filteContext.ExceptionHandled to TRUE,but the main problem was not solved,i cant set MODEL property of View,it is always null.

A: 

I may be mistaken, but I believe that the view data is part of the controller base and not actually part of the view itself. So you should be able to set the view data by doing such:

filterContext.Controller.ViewData.Model = <your view model>

I just tested and this worked for me. I don't see any reason why it shouldn't work for you:

public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        TestClass1 viewModel = new TestClass1();

        viewModel.FirstName = "TestFilter";

        filterContext.Controller.ViewData.Model = viewModel;
    }

Referencing documentation

joshlrogers
wow,i thought it works,but nope,that Model is always null in the view
@ozsenegal In your example you are in the OnActionExecuted event, but are you sure you are in it in your actual code? Your viewdata should be accessible at this point.
joshlrogers
yes,im sure.View data is acessible the way you show,but in the view the model property keeps null
@ozsenegal check my update. My code worked for me, it changed the view model to what I added in the filter.
joshlrogers
A: 

Maybe this will work for you:

filterContext.Result = new ViewResult { ViewName = "Exception", ViewData = new ViewDataDictionary(new CmsExceptionViewData(filterContext.Exception, action, controllerName, errorMessage)) };

So the ViewData is created with a ViewDataDictionary which accepts either a dictionary or a model.

Michiel