Calling ASP.NET MVC Action Methods from JavaScript?

Up vote 2 down vote favorite share g+ share fb share tw.

Thanks to all javascript" rel="nofollow">" rel="nofollow"> mvc razor link|improve this question edited Jan 21 at 14:33Rory McCrossan14.5k2926 asked Jan 21 at 12:26Milracle59116 88% accept rate.

Use jQuery ajax: function AddToCart(id) { $. Ajax({ url: 'urlToController', data: { id: id } success: function(){ alert('Added'); } }); }

1 thanks Kman, its working ... – Milracle Jan 21 at 12:36.

If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action: $(function(){ $('#sampleDiv'). Click(function(){ /* While this code is JavaScript, but because it's embedded inside a cshtml file, we can use Razor, and create the URL of the action */ var url = @Url. Action("ActionName", "Controller"); }); }).

Thanks saeed, for your useful help ... – Milracle Jan 21 at 12:35.

JQuery post is the short version of jQuery ajax. Function addToCart(id) { $. Post('cartController',{id:id } function(data) { //do whatever with the result.

}); } If you want more options like success callbacks and error handling, use jQuery ajax, function addToCart(id) { $. Ajax({ url: "cartController", data: { id: id }, success: function(data){ //call is successfully completed and we got result in data }, error:function (xhr, ajaxOptions, thrownError){ //some errror, some show err msg to user and log the error alert(xhr. ResponseText); } }); }.

If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions. ActionLink method. @Ajax.

ActionLink("Add To Cart", "AddToCart", new { productId = Model. ProductId }, new AjaxOptions() { HttpMethod = "Post" }); That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on.

Related Questions