對於這樣的解決方案,我建議你創建一個JavascriptController與上BookController的一個 「JavascriptActionResult」 或新 「JavascriptActionResult」以及輸出所需javascript的視圖。這樣你就可以用剃鬚刀動態地編寫Javascript,並且保證你的MVC的路由模式行爲將被遵循。與所有的設置,頁面將是:
<script type="text/javascript" src="@Url.Action("GetAllBooksJS","Book")"></script>
PS:沒有在MVC本地JavascriptActionResult,但你可以擴展的ActionResult來執行或簡單的力量,在經典的ActionResult功能的內容類型。
貝婁是我在MVC3中製作的一個工作案例。
控制器:
public class BookController : Controller
{
//
// GET: /Book/
public ActionResult Index()
{
return View();
}
public JsonResult GetAllBooks() {
return Json(new[] { new { name = "Book1" }, new { name = "Book2" } });
}
public ActionResult GetAllBooksJS()
{
Response.ContentType = "text/javascript";
return View();
}
}
索引視圖:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.7.1.min.js")"> </script>
<script type="text/javascript" src="@Url.Action("GetAllBooksJS","Book")"></script>
</head>
<body>
<div>
<button>Get books ajax</button>
</div>
</body>
</html>
GetAllBooksJS查看:
@{
Layout = null;
}
$(document).ready(function(){
$('button').on('click',function() {
GetBooksAjax();
});
});
function GetBooksAjax() {
$.ajax({
url: '@Url.Action("GetAllBooks","Book")',
type: 'POST',
dataType: 'json',
success: function(oJSON) {
$.each(oJSON,function(){
alert(this.name);
})
}
})
}
GetAllBooksJS查看V2,在第二個版本的JavaScript,只要它是裝由索引視圖,將參與阿賈克斯呼籲,我想你的情況:
@{
Layout = null;
}
function GetBooksAjax() {
$.ajax({
url: '@Url.Action("GetAllBooks","Book")',
type: 'POST',
dataType: 'json',
success: function(oJSON) {
$.each(oJSON,function(){
alert(this.name);
})
}
})
}
GetBooksAjax();
什麼錯誤會來嗎? –
@PKKG沒有錯誤,但操作方法沒有解除。 – Sampath