[c#] Making a Simple Ajax call to controller in asp.net mvc

I'm trying to get started with ASP.NET MVC Ajax calls.

Controller:

public class AjaxTestController : Controller
{
    //
    // GET: /AjaxTest/
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult FirstAjax()
    {
        return Json("chamara", JsonRequestBehavior.AllowGet);
    }   
}

View:

<head runat="server">
    <title>FirstAjax</title>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var serviceURL = '/AjaxTest/FirstAjax';

            $.ajax({
                type: "POST",
                url: serviceURL,
                data: param = "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {     
                alert(data);
            }

            function errorFunc() {
                alert('error');
            }
        });
    </script>
</head>

I just need to print an alert with the controller method returning data. Above code just print "chamara" on my view. An alert is not firing.

UPDATE

I modified my controller as below and it start working. I don't have an clear idea why it's working now. Some one please explain. The parameter "a" does not related i added it because i can not add two methods with same method name and parameters.I think this might not be the solution but its working

public class AjaxTestController : Controller
    {
        //
        // GET: /AjaxTest/
        [HttpGet]
        public ActionResult FirstAjax()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FirstAjax(string a)
        {
            return Json("chamara", JsonRequestBehavior.AllowGet);
        }
    }

This question is related to c# jquery asp.net asp.net-mvc asp.net-mvc-2

The answer is


If you just need to hit C# Method on in your Ajax Call you just need to pass two matter type and url if your request is get then you just need to specify the url only. please follow the code below it's working fine.

C# Code:

    [HttpGet]
    public ActionResult FirstAjax()
    {
        return Json("chamara", JsonRequestBehavior.AllowGet);
    }   

Java Script Code if Get Request

    $.ajax({
        url: 'home/FirstAjax',
        success: function(responce){ alert(responce.data)},
        error: function(responce){ alert(responce.data)}
    });

Java Script Code if Post Request and also [HttpGet] to [HttpPost]

        $.ajax({
            url: 'home/FirstAjax',
            type:'POST',
            success: function(responce){ alert(responce)},
            error: function(responce){ alert(responce)}
        });

Note: If you FirstAjax in same controller in which your View Controller then no need for Controller name in url. like url: 'FirstAjax',


It's for your UPDATE question.

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

UPDATE:

[HttpGet]
public ActionResult FirstAjax()
{
    Some Code--Some Code---Some Code
    return View();
}

[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
    Some Code--Some Code---Some Code
    return View();
}

And please refer this link for further reference of how a method becomes an action. Very good reference though.


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
});

Add "JsonValueProviderFactory" in global.asax :

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

First thing there is no need of having two different versions of jquery libraries in one page,either "1.9.1" or "2.0.0" is sufficient to make ajax calls work..

Here is your controller code:

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult FirstAjax(string a)
    {
        return Json("chamara", JsonRequestBehavior.AllowGet);
    }   

This is how your view should look like:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {
    var a = "Test";
    $.ajax({
        url: "../../Home/FirstAjax",
        type: "GET",
        data: { a : a },
        success: function (response) {
            alert(response);
        },
        error: function (response) {
            alert(response);
        }
    });
});
</script>

View;

 $.ajax({
        type: 'GET',
        cache: false,
        url: '/Login/Method',
        dataType: 'json',
        data: {  },
        error: function () {
        },
        success: function (result) {
            alert("success")
        }
    });

Controller Method;

 public JsonResult Method()
 {
   return Json(new JsonResult()
      {
         Data = "Result"
      }, JsonRequestBehavior.AllowGet);
 }

instead of url: serviceURL, use

url: '<%= serviceURL%>',

and are you passing 2 parameters to successFunc?

function successFunc(data)
 {
   alert(data);
 }

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'); }
});

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-2

Better solution without exluding fields from Binding How to set the value of a hidden field from a controller in mvc Making a Simple Ajax call to controller in asp.net mvc ASP.Net MVC - Read File from HttpPostedFileBase without save Session state can only be used when enableSessionState is set to true either in a configuration Using Tempdata in ASP.NET MVC - Best practice Getting index value on razor foreach Current date and time - Default in MVC razor Url.Action parameters? How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")