我正在为我的aspnet MVC应用程序使用visual studio serenity模板。例如,我想要做的是在控制器中每1秒生成一次随机值,并将其传递给cshtml页面<div>
。
请帮助我如何每隔1秒刷新一次页面。
[RoutePrefix("Dashboard"), Route("{action=index}")]
public class DashboardController : Controller
{
[Authorize, HttpGet, Route("~/")]
public ActionResult Index()
{
return View();
}
model Serene2.Common.DashboardPageModel
@{
ViewData["Title"] = "Dashboard";
ViewData["PageId"] = "Dashboard";
}
@section Head {
<link rel="stylesheet" href="~/Content/iCheck/flat/blue.css">
<link rel="stylesheet" href="~/Scripts/morris/morris.css">
<link rel="stylesheet" href="~/Scripts/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet" href="~/Scripts/datepicker/datepicker3.css">
<link rel="stylesheet" href="~/Scripts/daterangepicker/daterangepicker-bs3.css">
<link rel="stylesheet" href="~/Scripts/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<script src="~/Scripts/raphael/raphael-min.js"></script>
<script src="~/Scripts/morris/morris.min.js"></script>
<script src="~/Scripts/sparkline/jquery.sparkline.min.js"></script>
<script src="~/Scripts/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="~/Scripts/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<script src="~/Scripts/knob/jquery.knob.js"></script>
<script src="~/Scripts/daterangepicker/moment.min.js"></script>
<script src="~/Scripts/daterangepicker/daterangepicker.js"></script>
<script src="~/Scripts/datepicker/bootstrap-datepicker.js"></script>
<script src="~/Scripts/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<script src="~/Scripts/adminlte/pages/dashboard.js"></script>
<script src="~/Scripts/adminlte/demo.js"></script>
}
@section ContentHeader {
<h1>@LocalText.Get("Navigation.Dashboard")<small>@Html.Raw(Texts.Site.Dashboard.ContentDescription)</small></h1>
}
<div class="inner">
<p>My Random Value From Controller</p>
</div>
&#13;
答案 0 :(得分:3)
1.在cshtml中
<p id="pValue"></p>
<强> 2。在脚本中
var someRootPath = "@Url.Content("~")";
(function randomGenerator() {
$.ajax({
url: someRootPath + 'Dashboard/GetRandomValue',
success: function (data) {
$('#pValue').html(data.someValue);
},
complete: function () {
setTimeout(randomGenerator, 1000);
}
});
})();
最后
<强> 3.Controller 强>
[HttpGet]
public JsonResult GetRandomValue()
{
return Json(new { someValue = Guid.NewGuid().ToString() }, JsonRequestBehavior.AllowGet);
}
希望根据您当前的情况,这将有所帮助。
答案 1 :(得分:0)
如果您想每秒刷新一次页面,可以在页面上添加一些javascript:
<script type="text/javascript">
setTimeout(function(){ document.location.reload(); }, 1000);
</script>
如果您只想更新页面的部分,可以进行ajax调用(http://api.jquery.com/jquery.ajax/或https://developer.mozilla.org/nl/docs/Web/API/XMLHttpRequest),这将指向您的控制器操作 - 仅返回必要的数据。然后,再次使用javascript,您可以修改您认为相关的页面部分。