ajax call from controller

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
1 year ago
dears
i need to call endpoint from custom controller not core controller
public class PayTabsController : BaseController
    {
[ValidateAntiForgeryToken]
        [HttpPost]
        [Route("OnGetAddress")]
        public IActionResult OnGetAddress(string addressId, string customerId){}
}

and the view is
 $.ajax({
                    type: "POST",
                    url: '/PayTabs/OnGetAddress?addressId=' + addressId + '&customerId=' [email protected]().GetAwaiter().GetResult().Id,

and it said not found :(
add routeprovide or what to do? to make it work.
please help
and thanks inadvance
1 year ago
You could use route like
public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder)
{                                        
endpointRouteBuilder.MapControllerRoute("Nop.Plugin.FormatCurrencyForCurrentStore",
                "FormatCurrencyForCurrentStore",
                new { controller = "Apollo", action = "FormatCurrencyForCurrentStore" });

To call Controller Routine
        public async Task<IActionResult> FormatCurrencyForCurrentStore(decimal total = 0)
        {
            var totalbookingprice_wc = await _priceFormatter.FormatPriceAsync(total);
            return Json(new { Totalbookingprice = totalbookingprice_wc });
        }

From Ajax Call
            $.ajax({
                url: '/FormatCurrencyForCurrentStore',
                data: { total: total },
                dataType: "json",
                success: function (data) {
                    $("#lbl_total").text(data.Totalbookingprice);
                    //alert(data.Totalbookingprice);
                }
            });
1 year ago
thanks for help yidan
but still same error
controller
public class PayTabsController : BaseController
    {
public IActionResult OnGetAddress(string addressId, string customerId)
        {
            var customer = _workContext.GetCurrentCustomerAsync().GetAwaiter().GetResult();
            if (string.IsNullOrEmpty(addressId) || addressId == "0" || customerId != customer.Id.ToString())
            {

                return Json(new
                {
                    FirstName = customer.FirstName,
                    LastName = customer.LastName,
                    PhoneNumber = customer.Phone,
                    Email = customer.Email
                });
            }
            else
            {
                Address address = _addressService.GetAddressByIdAsync(int.Parse(addressId)).GetAwaiter().GetResult();
                return Json(new
                {
                    address.FirstName,
                    address.LastName,
                    address.PhoneNumber,
                    address.Email,
                    Address = address.Address1,
                    address.City,
                    State = address.Address2
                });
            }

        }
}

routeprovidor
        public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder)
        {
            endpointRouteBuilder.MapControllerRoute(name: "OnGetAddress",
                pattern: $"OnGetAddress",
                defaults: new { controller = "PayTabs", action = "OnGetAddress" });
}

and ajax

function getAddress(addressId) {
            if (addressId) {
                $("#main-loader").show("in");
                $.ajax({
                    type: "POST",
                    url: '/OnGetAddress',
                    //url: '/PayTabs/OnGetAddress?addressId=' + addressId + '&customerId=' [email protected]().GetAwaiter().GetResult().Id,
          data: {addressId: addressId,customerId: @workContext.GetCurrentCustomerAsync().GetAwaiter().GetResult().Id},
                    contentType: "application/json; charset=utf-8",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    dataType: "json"
                }).done(function (data) {
                    $("#FirstName").val(data.FirstName);
                    $("#LastName").val(data.LastName);
                    $("#PhoneNumber").val(data.PhoneNumber);
                    $("#Email").val(data.Email);
                    $("#City").val(data.City);
                    $("#Address").val(data.Address);
                    getDistricts(data.City, data.State);
                    $("#main-loader").hide("in");
                    }).fail(function (x, y, z) {
                        $("#main-loader").hide("in");
                    })
            }
            else {

            }
        }

error
POST https://localhost:44369/OnGetAddress 400

please help
1 year ago
jciibrahim wrote:
dears
i need to call endpoint from custom controller not core controller
public class PayTabsController : BaseController
    {
[ValidateAntiForgeryToken]
        [HttpPost]
        [Route("OnGetAddress")]
        public IActionResult OnGetAddress(string addressId, string customerId){}
}

and the view is
 $.ajax({
                    type: "POST",
                    url: '/PayTabs/OnGetAddress?addressId=' + addressId + '&customerId=' [email protected]().GetAwaiter().GetResult().Id,

and it said not found :(
add routeprovide or what to do? to make it work.
please help
and thanks inadvance



You are using [ValidateAntiForgeryToken] in your action method so you have to pass addAntiForgeryToken(data); in your ajax request.

read: {
                                            url: "@Html.Raw(Url.Action("ListLogs", "ActivityLog"))",
                                            type: "POST",
                                            dataType: "json",
                                            data: function() {
                                                var data = {
                                                    CreatedOnFrom: $('#@Html.IdFor(model => model.CreatedOnFrom)').val(),
                                                    CreatedOnTo: $('#@Html.IdFor(model => model.CreatedOnTo)').val(),
                                                    IpAddress: $('#@Html.IdFor(model => model.IpAddress)').val(),
                                                    ActivityLogTypeId: $('#ActivityLogTypeId').val()
                                                };
                                                addAntiForgeryToken(data);
                                                return data;
                                            }
                                        },
1 year ago
thanks alot Sangeet it works fine
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.