How to call an action from javascript or jquery in MVC 3 Razor

New article written at : How to call web api method using jquery ajax in ASP.NET MVC 4

Here there are two different requirements that I will look into

1. How to call an action form javascript or jquery and get a return value and then maybe use it somewhere on the view.

Below is an example of calling a controller action called “GetData” using javascript/jquery.

Here “GetData”┬áis the action I am going to call, so I have used Url.Action(“GetData”).

Note : strId is a value I am passing to the action, one more thing I observed is that you can only pass string variables to this method so whenever you define your action make sure that the parameter has string arguments only.

Js/Jquery Code

var url = '@Url.Action("GetData")';
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { value: strId},

success: function (result) {
$('#result).html(result);
}
});

Now *result *is what I will be returned from my action method, I could have returned say a JsonResult like the one below and then use result.foo or result.ball to get values “bar” / “dragon” out of them.

CSharp Code : Action Method (returning a Json)

public ActionResult GetData(string id)
{
    return Json(new {foo="bar", ball="dragon"});
}

New article written at : How to call web api method using jquery ajax in ASP.NET MVC 4

3 Comments

  1. Hi Yasser,

    i want to execute update action button if the user click on any input tag like check box ot drop down list, please give me any reference code to do my job.

    Regards,
    Madhu A

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>