Calling ASP.NET MVC Action Methods from JavaScript

后端 未结 8 1321
谎友^
谎友^ 2020-11-29 23:45

I have sample code like this:

 
      
8条回答
  •  有刺的猬
    2020-11-30 00:10

    You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d

    jQuery post is the short version of jQuery ajax.

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

    When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.

    This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.

提交回复
热议问题