我正在asp .net mvc 3中建立一个网站。
我正在尝试创建一个简单的切换按钮,可用于“添加到收藏夹”和 “从收藏中删除”。但是,如果用户已登录,我只想要此功能 否则我想引导他进入“登录”页面。
切换按钮效果很好,但不会检查用户是否已登录。如果一个 用户未登录然后单击按钮切换但不更新 数据库。我希望它直接进入登录页面。
我的代码如下:
查看:
<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();
}
});
}
控制器:
//
// 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);
}
如何在ajax发布之前检查用户是否已登录?如果他没有登录 如何将他引导至登录页面?
答案 0 :(得分:3)
如果用户未登录,为什么不直接显示您的登录操作的链接?您根本不需要jQuery - 当您第一次呈现页面时,您已经可以确定用户是否已登录,因此Ajax调用完全是多余的。
@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)
}
答案 1 :(得分:1)
您可以在所有ajax调用之后运行一个函数,并验证页面是否被重定向,例如,如果您的登录页面具有如下所示的h2标题:
<h2>Log On</h2>
您可以检测到并重定向自己:
$(document).ajaxComplete(function (e, xhr) {
if(xhr.responseText.indexOf("<h2>Log On</h2>") != -1) {
// redirect code here
}
});