从JavaScript调用ASP.NET MVC操作方法

我有这样的示例代码:

<div class="cart"> <a onclick="addToCart('@Model.productId');" class="button"><span>Add to Cart</span></a> </div> <div class="wishlist"> <a onclick="addToWishList('@Model.productId');">Add to Wish List</a> </div> <div class="compare"> <a onclick="addToCompare('@Model.productId');">Add to Compare</a> </div> 

如何编写JavaScript代码来调用控制器的操作方法?

使用jQuery ajax:

 function AddToCart(id) { $.ajax({ url: 'urlToController', data: { id: id } }).done(function() { alert('Added'); }); } 

http://api.jquery.com/jQuery.ajax/

如果你不需要太多的定制,并寻求简单,你可以用内置的方式–AjaxExtensions.ActionLink方法来完成 。

 <div class="cart"> @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" }); </div> 

该MSDN链接是必须读取的所有可能的重载此方法和AjaxOptions类的参数。 实际上,您可以使用确认,更改http方法,设置OnSuccess和OnFailure客户端脚本等

您正在调用addToCart方法并传递产品ID。 现在您可以使用jQuery ajax将这些数据传递给您的服务器端操作method.d

jQuery post是jQuery ajax的简短版本。

 function addToCart(id) { $.post('@Url.Action("Add","Cart")',{id:id } function(data) { //do whatever with the result. }); } 

如果你想要更多的select,如成功callback和error handling,使用jQuery ajax,

 function addToCart(id) { $.ajax({ url: '@Url.Action("Add","Cart")', 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); } }); } 

在进行ajax调用时,我强烈build议使用诸如Url.Action类的Html帮助器方法来生成操作方法的path。

这将工作,如果你的代码在剃刀视图,因为Url.Action将在服务器端由剃刀执行,并且C#expression式将被replace为正确的相对path。 但是,如果你在你的外部js文件中使用你的jQuery代码,你可以考虑在这个答案中提到的方法。

如果你想从你的JavaScript中调用一个动作,一种方法是在你的视图中embedded你的JavaScript代码(例如.cshtml文件),然后使用Razor创build一个该动作的URL:

 $(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 Don't forget to add '' around the url because it has to become a valid string in the final webpage */ var url = '@Url.Action("ActionName", "Controller")'; }); }); 

你可以简单地通过JavaScript调用一个Action Method

 var id = model.Id; //if you want to pass an Id parameter window.location.href = '@Url.Action("Action", "Controller")/' + id; 

希望这可以帮助…

当您使用相同的控制器redirect时,您可以简单地添加此项

 var url = "YourActionName?parameterName=" + parameterValue; window.location.href = url; 

你可以设置你的element

value="@model.productId"

onclick= addToWishList(this.value);

 Javascript Function function AddToCart(id) { $.ajax({ url: '@Url.Action("AddToCart", "ControllerName")', type: 'GET', dataType: 'json', cache: false, data: { 'id': id }, success: function (results) { alert(results) }, error: function () { alert('Error occured'); } }); } Controller Method to call [HttpGet] public JsonResult AddToCart(string id) { string newId = id; return Json(newId, JsonRequestBehavior.AllowGet); }