【发布时间】:2011-08-11 21:55:56
【问题描述】:
我已经看到这个问题被问了几种方法,解决方案通常适用于其他语言,不适用于 ASP.NET MVC 2。
我正在使用 Jquery 和 Jquery 表单以设定的时间间隔自动保存用户数据。我仍然希望应用程序能够超时,但通过 jquery 表单自动保存会不断刷新服务器。
我最初解决这个问题的想法很简单。我已经有一个 ActionFilter 用来查看会话是否过期。好吧,会话永远不会过期;但是,我只是根据会话中的值跟踪发生了多少自动保存,以及当它达到限制(在 web.config 中指定)时,它会执行以下操作:
filterContext.Result = new RedirectResult("~/Account.aspx/LogOn");
好吧,这不起作用,因为自动保存是在执行 ajaxFormSubmit 以首先调用该操作。我尝试将操作更改为重定向到登录页面,但同样的事情发生了......它只是不做重定向。该操作唯一可以返回的是 Json 结果。在我的最新版本(下面的代码)中,我将 json 返回值设置为 false 并调用 redirectToLogin() 函数将页面发送到登录页面。它不起作用,我不确定为什么。
对此的任何想法都会很有帮助。
设置视图自动保存间隔的代码摘录(放置在表单关闭之前):
<%
double sessionTimeoutInMinutes = double.Parse(ConfigurationManager.AppSettings["SESSION_TIMEOUT_IN_MINUTES"].ToString());
double maxContiguousAutoSaves = double.Parse(ConfigurationManager.AppSettings["MAX_CONTIGUOUS_AUTO_SAVES"].ToString());
double autoSaveInterval = (sessionTimeoutInMinutes / maxContiguousAutoSaves) * 60 * 1000;
%>
<%= Html.Hidden("autoSaveInterval", autoSaveInterval) %>
<script type="text/javascript">
$(document).ready(function() {
var autoSaveFrequency = $('[id=autoSaveInterval]').val();
//alert(' Auto Save Interval in miliseconds: ' + autoSaveFrequency);
setInterval(
"initAutoSave('AutoSaveGoals', 'message')"
, autoSaveFrequency);
});
</script>
“AutoSaveGoals”目标是我的一项操作的名称。它处理帖子,更新会话中的某些项目,并调用 repository.update。定义如下:
[HttpPost]
public ActionResult AutoSaveGoals(Data data)
{
Data sessdata = Data();
sessdata.MpaGoals = data.Goals;
sessdata.MpaStatus = data.MpaStatus;
sessdata.StartPeriodDate = data.StartPeriodDate;
sessdata.EndPeriodDate = data.EndPeriodDate;
sessdata.AssociatePassword = data.AssociatePassword;
try
{
_repository.update(sessdata);
}
catch (Exception e)
{
LogUtil.Write("AutoSaveGoals", "Auto Save Goals Failed");
LogUtil.WriteException(e);
}
if (!autoLogOffUser(RouteData.GetRequiredString("action")))
return Json(new { success = true });
else
return Json(new { success = false });
}
initAutoSave 函数是使用 Jquery & Jquery Forms 插件的 javascript。这里是:
function initAutoSave(targetUrl, messageDivId) {
var options = {
url: targetUrl,
type: 'POST',
beforeSubmit: showRequest,
success: function(data, textStatus) {
//alert('Returned from save! data: ' + data);
if (data.success) {
var currDateAndTime = " Page last saved on: " + getCurrentDateAndTime();
$('[id=' + messageDivId + ']').text(currDateAndTime).show('normal', function() { })
}
else {
alert('redirecting to login page');
redirectToLogin();
//$('[id=' + messageDivId + ']').text(' An error occurred while attempting to auto save this page.').show('normal', function() { })
//alert('ERROR: Page was not auto-saved properly!!!!');
}
}
};
$('form').ajaxSubmit(options);
}
我尝试在 redirectToLogin() 中进行 javascript 重定向,但它似乎没有获取 url 或者幕后的东西正在爆炸。以下是它的定义:
function redirectToLogin() {
window.location = "Account.aspx/LogOn";
}
【问题讨论】:
标签: c# javascript jquery .net asp.net-mvc