Calling ASP.NET MVC Action Methods from JavaScript

2019-01-08 12:17发布

I have sample code like this:

 <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>    

How can I write JavaScript code to call the controller action method?

8条回答
We Are One
2楼-- · 2019-01-08 12:54

You can simply add this when you are using same controller to redirect

var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
查看更多
SAY GOODBYE
3楼-- · 2019-01-08 12:56

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

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

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

查看更多
登录 后发表回答