对于这样的解决方案,我建议你创建一个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