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

About Yasser Shaikh

Hello, I am a Web Dev, employed with Media.Net where I primarily work on ASP.NET MVC and Angular JS based developement.

Questions? Enquiries? Comments? Or even just want to say “Hi” to me, you are welcome to all of that. Just drop me a message at “mail@yassershaikh.com” and I’ll get back to you as soon as possible.

Cheers !

2 comments

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>