Calling ASP.NET MVC Action Methods from JavaScript

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

I have sample code like this:

 
                      
相关标签:
8条回答
  • 2020-11-30 00:00

    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
    
             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")';
        });
    });
    
    0 讨论(0)
  • 2020-11-30 00:02

    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

    0 讨论(0)
  • 2020-11-30 00:04
    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);
      }
    
    0 讨论(0)
  • 2020-11-30 00:07

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

    var url = "YourActionName?parameterName=" + parameterValue;
    window.location.href = url;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 00:14

    Use jQuery ajax:

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

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

    0 讨论(0)
提交回复
热议问题