I need to get a list from mvc controller to view using jquery ajax. how can i do that. this is my code. Its alerting error message.
publ
you can do like this , return json data and print it
Read full tutorial : http://www.c-sharpcorner.com/UploadFile/3d39b4/rendering-a-partial-view-and-json-data-using-ajax-in-Asp-Net/
public JsonResult BooksByPublisherId(int id)
{
IEnumerable modelList = new List();
using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
{
var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();
modelList = books.Select(x =>
new BookModel()
{
Title = x.Title,
Author = x.Auther,
Year = x.Year,
Price = x.Price
});
}
return Json(modelList,JsonRequestBehavior.AllowGet);
}
javascript
$.ajax({
cache: false,
type: "GET",
url: "@(Url.RouteUrl("BooksByPublisherId"))",
data: { "id": id },
success: function (data) {
var result = "";
booksDiv.html('');
$.each(data, function (id, book) {
result += 'Title : ' + book.Title + '
' +
' Author :' + book.Author + '
' +
' Year :' + book.Year + '
' +
' Price :' + book.Price + '
';
});
booksDiv.html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve books.');
}
});