Making a Simple Ajax call to controller in asp.net mvc
asp.net, asp.net-mvc, c#, javascript, jquery
Solution
After the update you have done,
- its first calling the FirstAjax action with default HttpGet request and renders the blank Html view . (Earlier you were not having it)
- 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.
Problem
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); } } ```