John John
John John

Reputation: 1

What are the differences between Ajax & getJSON when calling an action method that return JSON

I am reading a book about asp.net MVC and I found different methods for calling Action methods that return JSON:, either using Ajax OR getJSOn, so are these two methods equivalent to:-

$.ajax({
type: "GET",
url: "http://localhost:11279/test/testcall",
dataType: "json",
success: function (result) {
var message = result.Title + ": $" + result.CurrentPrice;
$('#Result').html(message);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});

And the getJSON is:-

<script type="text/javascript">
$(function () {
$.getJSON("http://localhost:11279/test/testcall",
function (data) {
$.each(data, function (key, val) {
var str = val.Description;
$('<li/>', { html: str }).appendTo($('#auctions'));
});
});
});
</script>

Second question

if I want to call the above action method or an external web service from a controller class instead of using javaScript, so which c-sharp methods I should use ?, and how I am going to pass the returned JSON from the controller class to the view. BR

Upvotes: 1

Views: 3058

Answers (1)

Pranay Rana
Pranay Rana

Reputation: 176934

getJson- Method allow get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed.

Ajax ()- This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter

  • Provide more control on the data sending and on response data.
  • Allow to handle error occur during call.
  • Allow to handle data if the call to ajax page is successfull.

Answer to 2

You can make use of jquery + Ajax() function to consume it in your html page..

here is article for you : Steps to Call WCF Service using jQuery.

something like this

function WCFJSON() {
             var userid = "1";
             Type = "POST";
             Url = "Service.svc/GetUser";
             Data = '{"Id": "' + userid + '"}';
             ContentType = "application/json; charset=utf-8";
             DataType = "json"; varProcessData = true; 
             CallService();
         }

//function to call WCF  Service       
         function CallService() {
             $.ajax({
                 type: Type, //GET or POST or PUT or DELETE verb
                 url: Url, // Location of the service
                 data: Data, //Data sent to server
                 contentType: ContentType, // content type sent to server
                 dataType: DataType, //Expected data format from server
                 processdata: ProcessData, //True or False
                 success: function(msg) {//On Successfull service call
                     ServiceSucceeded(msg);
                 },
                 error: ServiceFailed// When Service call fails
             });
         }

Upvotes: 1

Related Questions