We have often seen action returns a View method. Optionally we can also pass the view name and the other parameters in the View method. Most of the time we return a view as ActionResult to navigate.



public ActionResult About()
        {
                    
            ViewBag.Message = "Your application description page.";
            return View();
        }

Now I have a requirement to navigate to Login view or return Login view on the basis of some authorization check. There are various ways you can do this however the approach I selected required me to override the OnActionExecuting() method in the controller class.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var result = _authorizeService.CanSeeTheAboutView(userId);   
            if(!result)
            {
                filterContext.Result = View("Account/Login");
            }
            base.OnActionExecuting(filterContext);
        }

Type of the filter context result is ActionResult, so its value can be set to a View. To navigate I set the value of the filterContext.Result as View with view name as parameter.

Simple ? but it did not work, and I got the exception as follows:

imageKeep in mind that I am trying to navigate to the Login view which is part of the Account controller from Home controller. However If you are navigating to view from same controller, you won’t get the above exception. Essentially we are trying cross controller view navigation. To get rid of above exception, I had to use RedirectToAction().

protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var result = _authorizeService.CanSeeTheAboutView(userId);   
            if(!result)
            {
                filterContext.Result = RedirectToAction("Login", "Account");
            }
            base.OnActionExecuting(filterContext);
        }


Another difference is RedirectToRoute make another request and View returns HTML to render and it does not make new request. Conclusion is use RedirectToAction if you are doing cross controller navigation. Any other thought?

Happy coding.

Advertisements

One thought on “RedirectToAction or View as ActionResult in ASP .Net MVC5 ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s