Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp .net mvc3 + check if user is logged in when using $.ajax post

I am building an website in asp .net mvc 3.

I am trying to create a simple toggle button which can be used to "Add to favorite" and "Remove from favorite". However, I only want this functionality if the user is logged in otherwise I want to direct him to the "Login" page.

The toggle button works well but it does not check if the user is logged in or not. If a user is not logged in then on clicking the button it toggles but does not update the database. I want it to direct to the login page.

My code is below:

View:

<div class="save-unsave-link">
    @if(Model.IsPropertySaved) {
        @Html.ActionLink("Remove Property", "RemoveSavedProperty", "Property", new { id = Model.Property.PropertyId }, new { @class="unsave-property", onclick = "saveProperty();" })      
    } else {
        @Html.ActionLink("Save Property", "AddSavedProperty", "Property", new { id = Model.Property.PropertyId }, new { @class="save-property", onclick = "saveProperty();" })
    }
</div>

jQuery:

function saveProperty() {
    $('.save-unsave-link').delegate("a", "click", function (e) {
        var id = $(this).attr('href').match(/\d+/);
        if ($(this).hasClass('unsave-property')) {
            $.ajax({
                url: this.href,
                dataType: "text json",
                type: "POST",
                data: {},
                success: function (data, textStatus) { }
            });
            $(this).removeClass().addClass("save-property")
                .attr('href', '/Property/RemoveSavedProperty/' + id)
                .text('Remove Property');
            e.preventDefault();
        } else {
            var id = $(this).attr('href').match(/\d+/);
            $.ajax({
                url: this.href,
                dataType: "text json",
                type: "POST",
                data: {},
                success: function (data, textStatus) { }
            });
            $(this).removeClass().addClass("unsave-property")
                .attr('href', '/Property/AddSavedProperty/' + id)
                .text('Save Property');
            e.preventDefault();
        }
    });
}

Controller:

//
// POST: /Property/AddSavedProperty
[HttpPost]
[Authorize]
public void AddSavedProperty(int id)
{
    websiteRepository.AddSavedProperty(id);
}

//
// POST: /Property/RemoveSavedProperty
[HttpPost]
[Authorize]
public void RemoveSavedProperty(int id)
{
    websiteRepository.RemoveSavedProperty(id);
}

How do I check if the user is logged in before ajax post? and if he is not logged in then how do I direct him to the login page?

like image 362
Tripping Avatar asked Nov 21 '12 21:11

Tripping


2 Answers

Why not just render out a link to your Login action if the user isn't logged in? You don't need jQuery for this at all - the Ajax call is completely superfluous when you can already determine whether the user is logged in when you first render the page.

@if (User.Identity.IsAuthenticated)
{
    @Html.ActionLink("Save Property", "AddSavedProperty", "Property", new { id = Model.Property.PropertyId },
        new { @class="save-property", onclick = "saveProperty();" })
}
else
{
    @Html.ActionLink("Save Property", "Login", "Login",
        new { returnUrl = ViewContext.HttpContext.Request.Url.PathAndQuery }, null)
}
like image 57
Ant P Avatar answered Oct 16 '22 10:10

Ant P


You can run a function after all ajax calls and verify if the page was redirected, for instance, if your login page has a h2 title like this:

<h2>Log On</h2>

You could detect it and redirect yourself:

$(document).ajaxComplete(function (e, xhr) {
    if(xhr.responseText.indexOf("<h2>Log On</h2>") != -1) {
       // redirect code here
    }
});
like image 22
thitemple Avatar answered Oct 16 '22 10:10

thitemple