Calling Controller Method Using AJAX

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
8 years ago
Hi All

I am trying to access the ProductController from AJAX Call

I have added the following method to the ProductController class

  public ActionResult test()
        {
            return null;
        }


And I am trying to access it from the _ProductBox.cshtml  like so

function onQuickViewClick(id, name){
        //show loading image
        try{
            //fetch and populate data
            document.getElementById("modal1Title").innerHTML = name;

            $.ajax({
                url: "productcontroller/test",
                data: {},
                type: "POST",
                contentType: "application/json; charset=utf-8",
                processData: false,
                dataType: "json",
                success: success,
                error: fail
            });

        }
        catch (e) {
            alert(e.message);
        }
        
    }

    function success(results) {
        alert("accessed");
    }

    function fail(err) {
        alert(err.status + " " + err.statusText);
    }


Please help me with this somebody.  What I am trying to achieve is pull the product details via AJAX call and display that in a popup modal

You help would be greatly appreciated!
8 years ago
I have updated my code as follows but I now get a new error.

"A route named 'test' could not be found in the route collection."


This is in ProductController.cs

 [HttpPost]
        public ActionResult test()
        {
                return Json(new
                {
                    success = true,
                    message = "working"
                });
        }





This is on _ProductBox.cshtml

testLink gets passed into the JS when 'quick view' button is clicked.

@{
var testLink = Url.RouteUrl("test");
}

<script type="text/javascript">

  function onQuickViewClick(id, name, link){
        //show product quick view data
        
        //show loading image
        try{
            //fetch and populate data
            document.getElementById("modal1Title").innerHTML = name;

            $.ajax({
                cache: false,
                url: link,
                type: 'post',
                success: success,
                error: fail
            });

        }
        catch (e) {
            alert(e.message);
        }
        
    }

    function success(results) {
        alert("accessed");
    }

    function fail(err) {
        alert(err.status + " " + err.statusText);
    }
</script>
8 years ago
Orion wrote:
I have updated my code as follows but I now get a new error.

"A route named 'test' could not be found in the route collection."


This is in ProductController.cs

...

  function onQuickViewClick(id, name, link){
        //show product quick view data
        
       .....
    }
</script>
[/code]



Hi Orion!

Don't waste your time ...have a look at ... https://www.nopcommerce.com/p/1566/bs-quick-view-plugin-free.aspx
and I hope it's exactly what you are looking for :)
Best Regards.
8 years ago
Hi abch,

I have already looked at that plugin.  it is built for v3.40 and it's not responsive.

I would also still need to use this method for other features. so it is important that I understand how to apply it.

Thank you for your input though, much appreciated.
8 years ago
hi try this


the js code is in attached file and I use RenderPartialViewToString
u can send 2 vars to that method u can extend it
in this case I send widgetZone
the TargetDiv iID is dynamic so u can create several item on one page

controller:


[HttpPost]
        [ValidateInput(false)]
        public ActionResult Carousels(string var1 = "", string var2 = "")
        {
            var carousels = _carouselService.GetCarouselsByWidgetZones(var1);
            var model = new CarouselListModel();
            foreach (var c in carousels)
            {
                model.AvailableCarousels.Add(PrepareCarouselModel(c));
            }

            return Json(new
            {
                html = this.RenderPartialViewToString("~/Plugins/Widgets.Carousel/Views/Carousels.cshtml", model),
            });
        }


view:



<div id="@zoneId" style="min-height:100px;">
    <div id="@(zoneId)-please-wait" class="please-wait-small" style="display:none;"> @T("Windalert.Common.Pleasewait")</div>

<script type="text/javascript">
    AjaxLoaderPlugin.init("@zoneId", "@(Url.Action("Carousels", "WidgetsCarousel"))", "@ViewBag.widgetZone", "");
    AjaxLoaderPlugin.action();
</script>


javascript file :


var AjaxLoaderPlugin = {
    objectName: false,
    actionUrl: false,
    var1: false,
    var2: false,
    init: function (objectName, actionUrl, var1, var2) {
        this.objectName = objectName;
        this.actionUrl = actionUrl;
        this.var1 = var1;
        this.var2 = var2;
    },
    action: function () {
        var targetDiv = $('#' + this.objectName);
        var targetPleaseWaitDiv = $('#' + this.objectName + '-please-wait');
        targetPleaseWaitDiv.show();
        $.ajax({
            cache: false,
            url: this.actionUrl,
            data: { "var1": this.var1, "var2": this.var2},
            type: 'post',
            success: function (data) {
                if (data.error) {
                    targetDiv.html(data.error);
                }
                if (data.html) {
                    targetPleaseWaitDiv.hide();
                    targetDiv.replaceWith(data.html);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Failed.');
            }
        });
    },
};
2 years ago
NOPCOMMERCE 4.3

I am trying to call controller action with this ajax request :

var form = $('#quote-list-shipping-address-form-@(Model.VendorId)').serialize();
                                    var postData = "?ShippingAddressId=" + $("#shipping-address-select-@(Model.VendorId)").val();
                                    $.ajax({
                                        cache: false,
                                        url: 'quotelist/selectnewshippingaddressforquote' + postData,
                                        data: form,
                                        type: "POST",
                                        dataType: 'json',
                                        success: function(data, result) {
                                            if (data && data.success) {
                                                // Refresh Page
                                                location.reload();
                                            }
                                        },
                                        error: function (xhr, opt, ajaxOptions) {
                                            console.log(xhr.responseText);
                                        }
                                    });


Route Provider :

            endpointRouteBuilder.MapControllerRoute("SaveNewShippingAddressForQuote", $"{pattern}quotelist/selectnewshippingaddressforquote",
                new { controller = "ShoppingCart", action = "SaveNewShippingAddressForQuote" });


Controller Action :


        [HttpPost, ActionName("Quotelist")]
        [FormValueRequired("savecustomershippingaddress")]
        public virtual ActionResult SaveNewShippingAddressForQuote(QuotelistModel.QuoteListShippingAddressModel model, IFormCollection form){}



Post - Button :

<button type="button" style="text-align:center;display:inline-block" id="btn-save-new-shipping-address-@(Model.VendorId)" name="savecustomershippingaddress" class="btn btn-primary">@T("QuoteCart.AddNewShippingAddress")</button>


But, everytime I am getting Page Not Found.
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.