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);
}
}
Add "JsonValueProviderFactory" in global.asax :
Use a Razor to dynamically change your URL by calling your action like this:
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:
And please refer this link for further reference of how a method becomes an action. Very good reference though.
After the update you have done,
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.
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.
Note: If you FirstAjax in same controller in which your View Controller then no need for Controller name in url. like
url: 'FirstAjax',
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:From your update: