Basvo
Basvo

Reputation: 156

Saving current url in controller before navigating away from page

for some reasons I need to save the url from the page the user is navigating away from to use it in other views and controllers. I.E: the user is on www.page1.com and is navigating to www.page2.com, then I want to save the url from www.page1.com somehow.

I already did some research and tried some things, first I was looking for cookies, but for a lot of reasons I want to ignore this possible solution. Then I was looking for a solution which was using JQuery to set the MVC Session variables, which did not work because those where server side. At last I came up with a possible soluiton, which was making an AJAX call to the controller and using the UserProfile(which I did create in my app) to save the url being navigated away from.

This is the code I was using:

The View:

$("a").on('click', function(e) {
            $.ajax({
                url: '<%= Url.Action("SetPreviousPage") %>',
                type: 'POST',
                data: $(location).attr('href');,
                success: function() {
                    alert("Success");
                },
                error: function(xhr, status, error) {
                    alert(error.toString());
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });
        });

The controller:

public JsonResult SetPreviousPage(string url)
    {
        FactsProfile.GetProfile().PreviousPage = url;
        return Json(url);
    }

For some reason this doesn't work, and I'm getting an error in my AJAX call in which I can't see what actually went wrong.

So two questions.

1: Is this the right way of completing this task? Or is this to much work for such a small task? 2: What is going wrong in my method? And how can I check where the problem came from.

Upvotes: 0

Views: 228

Answers (1)

Dabbas
Dabbas

Reputation: 3230

have you tried to use Request.UrlReferrer I remember it gives you the url you where in before moving to this new one.

Upvotes: 1

Related Questions