Calling ASP.NET MVC Action Methods from JavaScript?

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

Thanks to all javascript asp.net" rel="nofollow">asp.net-mvc asp.net" rel="nofollow">asp.net-mvc-3 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'); } }); } api.jquery.com/jQuery.ajax.

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.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions