I've been reading on this for a while and found that you can call a controller action by using:
$.ajax("MyController/MyAction", function(data) {
alert(data);
});
Does this mean I should add the MicrosoftMvcAjax.js or the MicrosoftAjax.js along with the Jquery lib?
Also, what should the second parameter contain in the $.ajax() function?
Lastly, any other link in stackoverflow or outside of the site that could be helpful in asp.net mvc w/ ajax and jquery?
Thanks.
This question is related to
jquery
asp.net-mvc
ajax
You can easily call any controller's action using jQuery AJAX method like this:
Note in this example my controller name is Student
Controller Action
public ActionResult Test()
{
return View();
}
In Any View of this above controller you can call the Test() action like this:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "@Url.Action("Test", "Student")",
success: function (result, status, xhr) {
alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
},
error: function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
});
</script>
In response to the above post I think it needs this line instead of your line:-
var strMethodUrl = '@Url.Action("SubMenu_Click", "Logging")?param1='+value1+' ¶m2='+value2
Or else you send the actual strings value1 and value2 to the controller.
However, for me, it only calls the controller once. It seems to hit 'receieveResponse' each time, but a break point on the controller method shows it is only hit 1st time until a page refresh.
Here is a working solution. For the cshtml page:-
<button type="button" onclick="ButtonClick();"> Call »</button>
<script>
function ButtonClick()
{
callControllerMethod2("1", "2");
}
function callControllerMethod2(value1, value2)
{
var response = null;
$.ajax({
async: true,
url: "Logging/SubMenu_Click?param1=" + value1 + " ¶m2=" + value2,
cache: false,
dataType: "json",
success: function (data) { receiveResponse(data); }
});
}
function receiveResponse(response)
{
if (response != null)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i].Data);
}
}
}
</script>
And for the controller:-
public class A
{
public string Id { get; set; }
public string Data { get; set; }
}
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = new A[] {new A(){ Id = "1", Data = DateTime.Now.Millisecond.ToString() } };
return Json(arr , JsonRequestBehavior.AllowGet);
}
You can see the time changing each time it is called, so there is no caching of the values...
We can call Controller method using Javascript / Jquery very easily as follows:
Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = null;
try
{
Processing...
Get Result and fill arr.
}
catch { }
return Json(arr , JsonRequestBehavior.AllowGet);
}
Following is the complex type (class)
public class A
{
public string property1 {get ; set ;}
public string property2 {get ; set ;}
}
Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.
function callControllerMethod(value1 , value2) {
var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 ¶m2=value2'
$.getJSON(strMethodUrl, receieveResponse);
}
function receieveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].property1);
}
}
}
In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.
receieveResponse is the callback function receiving the response or return value of the controllers method.
Here we made use of JSON , since we can't make use of the C# class object
directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:
Json(arr , JsonRequestBehavior.AllowGet);
and returned that Json object.
Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.
For more detaill click here
the previous response is ASP.NET only
you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js
and then a similar block of code but simpler...
$.ajax({ url: '/Controller/Action/Id',
success: function(data) { alert(data); },
statusCode : {
404: function(content) { alert('cannot find resource'); },
500: function(content) { alert('internal server error'); }
},
error: function(req, status, errorObj) {
// handle status === "timeout"
// handle other errors
}
});
I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.
ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET
Source: Stackoverflow.com