I am building a website in asp.net mvc 3.
I am trying to create a simple toggle button that can be used for Add to Favorites and Remove from Favorites. 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 does not check if the user is logged in or not. If the user is not logged in, then by clicking the button that he switches, but does not update the database. I want him to go 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 to check if user is logged in before ajax post? and if he is not logged in, then how do I send him to the login page?