Sam Alekseev
Sam Alekseev

Reputation: 2391

ASP.NET MVC current request url (ajax call issue)

I use popular technique "ReturnUrl". I pass current page url to server, do some staff and then i redirect user back to this url. For example, user posts comment and then get back to this url.

@using (Html.BeginForm("AddUserComment", "Home", new { returnUrl = HttpContext.Current.Request.RawUrl }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}

BUT, when i load this form through ajax call, like this:

$.ajax({
        type: 'GET',
        url: '/Home/ShowUserCommentsBlock/',
        data: { entityType: entityType, entityId: entityId },
        cache: false,
        ...
    });

HttpContext.Current.Request.RawUrl returns ajax request url "/Home/ShowUserCommentsBlock?entityType=...", but i need current page url, where ajax request is called. What should I use instead of HttpContext object?

Upvotes: 3

Views: 4864

Answers (3)

ramiramilu
ramiramilu

Reputation: 17182

You can pass current page url as one of the property in AJAX request.

Say your AJAX request is in this way -

        $.ajax({
            url: "@Url.Action("Submit")",
            type: "POST",
            data: {
                Url: '@HttpContext.Current.Request.Url'
            , entitytype: 'this is type'
            },
            error: function (response) {
                if (!response.Success)
                    alert("Server error.");
            },
            success: function (response) {
                alert(response);
            }
        });

Then add one more parameter to your POST action with name Url. and you will get the url you are passing in ajax request there.

enter image description here

Put the Url in the Viewbag and then assign it to the ReturnUrl.

ViewBag.Url = Url;

And assignment as below -

@using (Html.BeginForm("Comments", "Ajax", new { returnUrl = ViewBag.Url}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{

}

Upvotes: 3

Sam Alekseev
Sam Alekseev

Reputation: 2391

Ok, i got this. We can use Request.UrlReferrer property for ajax requests to retrieve proper url, like this:

public ActionResult MyActionMethod()
{
            if (Request.IsAjaxRequest())
                ViewBag.ReturnUrl = HttpContext.Request.UrlReferrer.LocalPath;
            else
                ViewBag.ReturnUrl = HttpContext.Request.RawUrl;

            return View();
}

Upvotes: 6

Saffar
Saffar

Reputation: 149

You need to send the page's url with the ajax request (with the help of some razor inside the javascript code) then at the controller store it in the Viewbag for example then use it instead of HttpContext.Current.Request.RawUrl

Upvotes: 1

Related Questions