-1

enter image description hereI want to call a method from API Controller using AJAX. I have tried the following

I have added one hidden field in the view (like what we are doing in mvc controller)

<input type="hidden" id="GetShoppingCartUrl" value="@Html.Action("GetShoppingCartUrl","Cart")"/>

Then I have written ajax

function GetShoppingCart() {
            debugger;
            var url = $('#GetShoppingCartUrl').val();
            $.ajax({
                type: "get",
                url: url,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                },
                error: function () {
                }
            });
        }

But here it is not getting the method, GetShoppingCartUrl from the API Controller CartController. I want to call that method, what changes make it happening ?

Averla Team
  • 407
  • 1
  • 6
  • 16
  • is the `getShoppingCart` method getting called? Also you don't really need to save the url in the hidden input. You can just directly call it based on your mapping. – forJ Sep 15 '17 at 06:30
  • Firstly its `value="@Url.Action(...)` (not `@Html.Action()`) - but use a `data-` attribute, not a hidden input or just include it in the function - var url = '@Url.Action(..);` if the script is not in an external file –  Sep 15 '17 at 06:38
  • @serendipity method is not hitting. – Averla Team Sep 15 '17 at 06:38
  • @AverlaTeam then call the method.. `GetShoppignCart()` And as I already said just directly map the `url`. `/api/controllerName/methodName/id` unless you've changed it – forJ Sep 15 '17 at 06:41
  • @serendipity I have tried that too – Averla Team Sep 15 '17 at 06:49
  • @AverlaTeam what does your route template look like – forJ Sep 15 '17 at 07:05
  • @AverlaTeam inside WebApiConfig.cs – forJ Sep 15 '17 at 07:06

2 Answers2

0
 function GetShoppingCart() {
                debugger;
                var url = "Cart/GetShoppingCartUrl"
                $.ajax({
                    type: "get",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                    },
                    error: function () {
                    }
                });
            }

you can directly put your actionlink in the url Hope it helps. :)

newbieeee
  • 21
  • 5
0

Use this below code to get the url of your site in javascript and append it before the url in ajax call. e.g var url = baseUrl+ "Cart/GetShoppingCartUrl";

@{ string url = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath; if(url[url.Length-1]!='/') { url =url+ "/"; } } var baseUrl = '@url'; //alert(baseUrl);
Karthik U
  • 1
  • 1