Uçan Kartal Uçan Kartal - 2 months ago 11
C# Question

Pass parameter to Ajax safe way

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?

Answer

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.

Comments