在ASP.net mvc网站中设置计时器

时间:2017-01-12 19:33:59

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 asp.net-mvc-5

在付款窗口中当客户点击付款按钮时,我想启动计时器。如果付款处理花费超过5秒,我想重定向到一个页面。以下是我能想到的。

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SavePayment(PaymentFormMV data)
        {
            if (Session["startTime"] == null)
            {
                Session["startTime"] = DateTime.Now;
            }

            var ticksRemaining = DateTime.Now - (DateTime)Session["startTime"];
           int x = int.Parse(ticksRemaining.ToString()); // Format Unhandled exception
            if(x == 5)
            {
                return RedirectToAction("Index", "Home");
            }
            // Payment Logic Here to 3rd Party API
             return View("PaymentConfirmation", returnData);
}

但是当我计算ticksRemaining时,它并没有像我期望的那样工作。我需要一些主题或其他东西。我是新手,请指导我。我只想查看按钮点击和当前时间之间的持续时间。如果它超过5秒我想将用户重定向到新页面。

3 个答案:

答案 0 :(得分:2)

在客户端实现这一点要合理得多。你可以使用JavaScript。例如,这可能对您有所帮助:

Page Redirect after X seconds wait using JavaScript

JQuery Redirect to URL after specified time

答案 1 :(得分:1)

TimeSpan ticksRemaining = DateTime.Now - (DateTime)Session["startTime"];
int x = ticksRemaining.TotalSeconds;

答案 2 :(得分:0)

在控制器中只需使用波纹管之类的东西

public ActionResult YourcurrentAction()
{
   TempData["msg"] = "Your desire message here";
   return RedirectToAction("Action_Which_You_Gonna_Redirect_To", "YourControlName");
}

现在处于重定向操作中,请使用以下代码

<center> <h2> @TempData["msg"].ToString() </h2> </center>
 @TempData.Remove("msg")

    <script type="text/javascript">
        window.setTimeout(function () {
            window.location.href = "Your_Desire_Link_To_Redirect";
        }, 5000);
    </script>

如果仅需要客户端,请使用我的代码第二部分。其他明智的选择是两者都用,但是需要的方式。

顺便说一句,请记住,如果要在不同动作之间移动,则必须使用TempData来存储示例中的message等值。并记住将其删除以释放使用后的内存。否则,请使用ViewBag。

希望对您有帮助,盖达尔;