使用ajax显示列表
问题描述:
为什么在点击按钮后显示什么都没有。它不会调用BooksByPublisherId
。我错过了什么?如何解决这个问题?使用ajax显示列表
控制器
public class FoodController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult BooksByPublisherId(int id)
{
IList<BookModel> modelList = new List<BookModel>();
modelList.Add(new BookModel { Author = "Jhon", Year = "1970" });
modelList.Add(new BookModel { Author = "Nick", Year = "1977" });
modelList.Add(new BookModel { Author = "Joseph", Year = "1978" });
return Json(modelList, JsonRequestBehavior.AllowGet);
}
}
型号
public class BookModel
{
public string Title { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public decimal Price { get; set; }
}
查看
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-2.2.0.js"></script>
<h2>Index</h2>
<button data-bind="click: capitalizeLastName">Load list</button>
<div class="results">Wait for list</div>
<script>
function AppViewModel() {
this.capitalizeLastName = function() {
debugger;
$.ajax({
cache: false,
type: "GET",
url: "Food/BooksByPublisherId",
data: { "id": id },
success: function (data) {
var result = "";
$.each(data, function (id, book) {
result += '<b>Title : </b>' + book.Title + '<br />' +
'<b> Author :</b>' + book.Author + '<br />' +
'<b> Year :</b>' + book.Year + '<br />' +
'<b> Price :</b>' + book.Price + '<hr />';
});
$('.results').html(result);
},
error: function (response) {
debugger;
alert('eror');
}
});
}
}
ko.applyBindings(new AppViewModel());
</script>
答
唯一的问题我可以在你的代码中看到的是,您使用的是被称为id
变量打造JS作为ajax调用的数据发送的对象,但未声明并初始化任何对象对它的价值。在这你会得到一个脚本错误,如
Uncaught ReferenceError: id is not defined
由于此脚本错误,您的其他js代码将无法正常工作!如你所见,错误是自我解释的。只需声明一个变量id
并为其设置一些值。
var id = 911;
$.ajax({
type: "GET",
url: "Food/BooksByPublisherId",
data: { "id": id },
// Your existing code
});
另外我看到你已经硬编码了你的动作方法的路径。更好的方法是使用Html帮助器方法(如Url.Action
)来构建操作方法的正确相对路径。
url: "@Url.Action("BooksByPublisherId","Food")",
这将工作,如果你的js代码是在剃刀视图内。如果您的代码位于外部js文件中,则可以使用this post中解释的解决方案。
您在浏览器控制台中遇到什么错误?并使用'@ Url.Action(“BooksByPublisherId”,“Food”)' –
正确地生成URL。我看到的唯一问题是在使用它之前,我没有看到'id'变量被定义并初始化为一个值。除此之外,代码看起来很好。同样如Stephen所说,总是使用助手方法为您的操作方法生成适当的相对url。如果你的js代码在一个外部的js文件中,请使用这个[answer]中提到的方法(http://stackoverflow.com/questions/34360537/how-do-i-make-js-know-about-the-application -root/34361168#34361168) – Shyju
通过'console.log(data)'给我们显示'console'中的'success'事件中的'data',以便它可以被轻松诊断 – anand