我正在尝试开发一个Mvc4应用程序,它有一个javascript来显示随机提示。但这些javascript只有在通过Index操作调用时才有效。我想用其他动作来处理javascript。请帮忙。
这是我的控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JQuaryError.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Test()
{
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
这是使用javascript的视图
@{
ViewBag.Title = "Home Page";
}
@section featured {
<script type="text/javascript" src="Scripts/jquery.js"></script>
<script type="text/javascript">
this.randomtip = function () {
var pause = 3000; // define the pause for each tip (in milliseconds) Feel free to make the pause longer so users can have time to read the tips :)
var length = $("#tips li").length;
var temp = -1;
this.getRan = function () {
// get the random number
var ran = Math.floor(Math.random() * length) + 1;
return ran;
};
this.show = function () {
var ran = getRan();
// to avoid repeating tips we need to check
while (ran == temp) {
ran = getRan();
};
temp = ran;
$("#tips li").hide();
$("#tips li:nth-child(" + ran + ")").fadeIn("fast");
};
// initiate the script and also set an interval
show(); setInterval(show, pause);
};
$(document).ready(function () {
randomtip();
});
</script>
}
<h3>We suggest the following:</h3>
<ul id="tips">
<li>... if you want to become a better coder you need to eat your vegetables?</li>
<li>... it takes more time to code a web page then to make a pizza?</li>
<li>... you should validate your code?</li>
<li>... jQuery is your friend? For real!</li>
<li>... no matter what some people claim, you can't learn CSS in 3 hours?</li>
</ul>
答案 0 :(得分:0)
如果您只在一个视图.cshtml
文件中包含了您的JavaScript代码,则只会为该操作的视图加载该代码。\ n \ n您可能知道,当控制器在每个操作中执行return View();
时,它将返回与ActionResult方法同名的视图。由于MVC是无状态的,因此当您从应用程序上的一个页面移动到另一个页面时,不会传递任何状态信息,因此当您在视图之间移动时,不会保留脚本/ css /其他任何内容。这意味着对于每个操作,您都需要将脚本包含在相应的.cshtml
文件中。
也就是说,如果您知道要将其包含在的每个视图中,您可以创建一个所有视图都将使用的布局视图。这样,您可以将要使用的JavaScript脚本放在布局中的所有视图中,并且您不必在每个单独的视图中复制它。