Red Wei
Red Wei

Reputation: 940

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?

Upvotes: 2

Views: 196

Answers (2)

richb01
richb01

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

Daniel Tran
Daniel Tran

Reputation: 6171

You need to use

 encodeURIComponent(Id)

Upvotes: 1

Related Questions