Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect a page in PartialViewResult() method

Hi I am trying to redirect a page when certain condition is not page using PartialViewResult method . But i am unable to do it. My code is like as follow :

public PartialViewResult Visit()
{    
    int visit = 0;
    if (base.IsLoggedIn() == true)
    {
        visit++;
    }
    else
    {
        // toDO redirect to home/index page
    }
}
like image 969
Dewasish Mitruka Avatar asked Nov 24 '25 14:11

Dewasish Mitruka


2 Answers

The code snippet you provided will not compile. You must return a result from all code paths. Try something like this:

public ActionResult Visit()
{
    int visit = 0;

    if (base.IsLoggedIn() == true)
    {
        visit++;
        return PartialView();
    }
    else
    {
        return RedirectToAction("ACTION_NAME_GOES_HERE");
    }
}

UPDATE:

I believe I now understand what you're trying to accomplish. In the event an ajax request is made by a user who is not logged in, you would like the browser to redirect the user. I suggest modifying your action method as follows:

public ActionResult Visit()
{
    int visit = 0;

    if (base.IsLoggedIn())
    {
        visit++;
        // whatever else needs to be done
        return PartialView();
    }
    else
    {
        // Note that this could be done using the Authorize ActionFilter, using
        // an overriden Authorize ActionFilter, or by overriding OnAuthorize().
        if (!base.IsLoggedIn())
            return new HttpUnauthorizedResult();
    }
}

Assuming that you have configured in your web.config, the response will be a 302 Redirect which is not what you want in this scenario. See Phil Haack's blog post which explains how this ASP.NET behavior can be prevented and a 401 Unauthorized response can be returned:

http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx

Then, assuming you're using jQuery to issue the AJAX request, you can handle the 401 response:

$.ajax({
    url: '/your_controller/visit',
    type: 'GET',
    statusCode: {
        200: function (data) {
            // data = your partialview
        },
        401: function (data) {
            location.href = '/the_path/to_redirect/to';
        }
    }
});
like image 89
Phil Klein Avatar answered Nov 27 '25 03:11

Phil Klein


Not sure I fully understand the issue but this might help someone as it worked for me.

else
{
    Response.Redirect("~/default.aspx");
    return null;
}
like image 34
RayLoveless Avatar answered Nov 27 '25 03:11

RayLoveless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!