使用 ajax 显示列表

Display list using ajax

本文关键字:列表 显示 ajax 使用      更新时间:2023-09-26

为什么点击按钮后它什么都不显示。并且它不会调用BooksByPublisherId.我错过了什么?如何解决这个问题?

控制器

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 的变量来构建你作为 ajax 调用数据发送的 js 对象,但它没有声明和初始化它的任何值。在这种情况下,您将获得一个脚本错误,例如

捕获的引用错误:未定义 id

由于此脚本错误,您的其他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 文件中,您可以使用本文中解释的解决方案。