Reputation: 940
I want to pass the id to the controller (ASP.NET MVC 5) and get the result from the controller. I have the following code:
function LoadBook(id) {
$.ajax({
url: '/Book/GetBookById' + id,
type: 'get',
dataType: 'json',
success: function (data) {
},
error: function (err) {
alert("Error: " + err.responseText);
}
})
}
Is it safe to do url: '/Book/GetBookById' + id? And if it doesn't safe, is there any way to do this?
Upvotes: 2
Views: 196
Reputation: 1117
The prescribed way to do this is:
public JsonResult GetBookById(int id)
{
// do your getting here
var yourdata = MyDataAccessClass.getBookById(id);
return new Json(yourdata, JsonRequestBehavior.AllowGet);
}
Your AJAX url would then be:
function LoadBook(id) {
$.ajax({
url: '/Book/GetBookById/' + id,
type: 'get',
dataType: 'json',
success: function (data) {
},
error: function (err) {
alert("Error: " + err.responseText);
}
})
}
This is the "safe" and standard way to make calls in Microsoft's MVC.
Upvotes: 1