2

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?

2
  • 1
    You need to URL-encode your parameter. Commented Sep 11, 2016 at 1:47
  • If you're looking for a RESTful way to do this, your URL should look like /Book/[id] or /Book/GetBookById/[id] (the second way seems redundant to me). Non-RESTful you could do /Book/GetBookById?id=[id]. That said, the VS tools could scaffold this for you automatically. Commented Sep 11, 2016 at 1:52

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

You still need to escape the parameter.
Only if it's not an integer. In my example it is, so no escaping is needed. Of course, it's not clear what the data type is in the OP's code. :-)
@richb01: Just because the parameter is declared as an integer doesn't mean that id in the JS is always an integer. It could have a query string or ../some other action and be used to attack things.
@UçanKartal: Learn about URL encoding.
@richb01: No. If id is 1?secretParam=blah or ../DeleteBook/24, no error will be thrown.
|
1

You need to use

 encodeURIComponent(Id) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.