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

chamara picture chamara · Apr 24, 2013 · Viewed 446.9k times · Source

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

Answer

Darren picture Darren · Apr 24, 2013

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