简体   繁体   中英

ASP.NET MVC return ViewResult

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 don't know how to pass it using ViewResult class directly.

Any ideas?

UPDATED: I've solved my problem setting filterContext.ExceptionHandled to TRUE,but the main problem was not solved, I can't set Model property of View , it is always null.

I ran into the same issue where my Model being passed to the View was always NULL. I was able to pass the Model to my view with the following:

Create your viewModel and set the properties. Create a new ViewResult giving it the name of your View and then pass your viewModel into the ViewData.

public override void OnActionExecuted(ActionExecutedContext filterContext)
{

    TestViewModel viewModel = new TestViewModel; 

    //Here set all the properties of your viewModel such as your exception message

    filterContext.Controller.ViewData.Model = viewModel;
    filterContext.Result = new ViewResult { ViewName = "Login", ViewData = new ViewDataDictionary(viewModel)};
    filterContext.ExceptionHandled = true;

}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM