这是我的BookController.cs文件 在这里我试图通过json访问我的数据库 它有两个类,第一个是动作结果书,第二个是json结果
public ActionResult Book()
{
return View();
}
//1 request failed is shown here.....
public JsonResult GetAllBook()
{
List<Book> allBook = new List<Book>();
// Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
using (LibraryManagmentSystemDBEntities dc = new LibraryManagmentSystemDBEntities())
{
allBook = dc.Books.ToList();
}
return new JsonResult { Data = allBook, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
这是我的查看文件Book.cshtml脚本部分。 即将到来的问题是它没有从数据库中获取数据。 相反,它给出了一个错误:
警报(“失败!请重试。”)
如果我截断数据库中的数据,则仅显示标题 “图书ID”,“图书名称”,“图书序列号”,“图书付款人”,“图书出版商名称”
$(document).ready(function ()
{
var hosturl = "http://" + window.location.hostname + ':' + window.location.port + "/Books/GetAllBook";
console.log(hosturl);
// This is for Get All Data
$("#btnAllBook").click(function ()
{
$.ajax(
{
url: hosturl,
data: "",
type: "GET",
dataType: "json",
success: function (data)
{
loadData(data);
},
error: function ()
{
alert("Failed! Please try again.");
}
});
});
function loadData(data)
{
// Here we will format & load/show data
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Book ID</th>');
thead.append('<th>Book Name</th>');
thead.append('<th>Book Serial Number</th>');
thead.append('<th>Book Auther</th>');
thead.append('<th>Book Publisher</th>');
tab.append(thead);
$.each(data, function (i, val)
{
// Append database data here
var trow = $('<tr></tr>');
trow.append('<td>' + val.BookID + '</td>');
trow.append('<td>' + val.BookName + '</td>');
trow.append('<td>' + val.BookSerialNumber + '</td>');
trow.append('<td>' + val.BookAuther + '</td>');
trow.append('<td>' + val.BookPublisher + '</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#UpdatePanel").html(tab);
};
});