Making a Simple Ajax call to controller in asp.net mvc Making a Simple Ajax call to controller in asp.net mvc asp.net asp.net

Making a Simple Ajax call to controller in asp.net mvc


Remove the data attribute as you are not POSTING anything to the server (Your controller does not expect any parameters).

And in your AJAX Method you can use Razor and use @Url.Action rather than a static string:

$.ajax({    url: '@Url.Action("FirstAjax", "AjaxTest")',    contentType: "application/json; charset=utf-8",    dataType: "json",    success: successFunc,    error: errorFunc});

From your update:

$.ajax({    type: "POST",    url: '@Url.Action("FirstAjax", "AjaxTest")',    contentType: "application/json; charset=utf-8",    data: { a: "testing" },    dataType: "json",    success: function() { alert('Success'); },    error: errorFunc});


After the update you have done,

  1. its first calling the FirstAjax action with default HttpGet requestand renders the blank Html view . (Earlier you were not having it)
  2. later on loading of DOM elements of that view your Ajax call get fired and displays alert.

Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.

You can't directly render JSON its plain data not HTML.


Use a Razor to dynamically change your URL by calling your action like this:

$.ajax({    type: "POST",    url: '@Url.Action("ActionName", "ControllerName")',    contentType: "application/json; charset=utf-8",    data: { data: "yourdata" },    dataType: "json",    success: function(recData) { alert('Success'); },    error: function() { alert('A error'); }});