Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in index.cshtml i use ajax in click event of .removelink to get changes from action controller
As follows :


$(".RemoveLink").click(function () {<br />
                    // Get the id from the link<br />
                    var recordToDelete = $(this).attr("data-id");<br />
                    if (recordToDelete != '' || recordToDelete != null) {<br />
                        // Perform the ajax post                             <br />
                    $.ajax({<br />
                            //contentType: 'application/json',<br />
                            //dataType: 'text',<br />
                            type: 'post',<br />
                            dataType: 'JSON',<br />
                            url: '/ShoppingCart/RemoveFromCart/',<br />
                            data: { id: recordToDelete },<br />
                            success: function (data) {  <br />
                                if (data.ItemCount == 0) {<br />
                                    $('#row-' + data.DeleteId).fadeOut('slow');<br />
                                }<br />
                                else {<br />
                                    $('#item-count-' + data.DeleteId).text(data.ItemCount);<br />
                                }<br />
                                $('#cart-total').text(data.CartTotal);<br />
                                $('#update-message').text(data.Message);<br />
                                $('#cart-status').text('Cart (' + data.CartCount + ')');<br />
                            }<br />
                        });                   <br />
                    }               <br />
                });




and in controller:


<pre>//AJAX: /ShoppingCart/RemoveFromCart/5<br />
        [HttpPost]<br />
        public IActionResult RemoveFromCart(int id)<br />
        {<br />
            //Remove the item from the cart<br />
            var cart = ShoppingCart.GetCart(this.HttpContext);<br />
            // Get the name of the album to display confirmation<br />
            //string albumName = _context.Carts<br />
            //.Single(item => item.RecordId == id).Album.Title;<br />
            Cart cartt = ShoppingCart.getCartForGetalbumName(id);<br />
            // Remove from cart<br />
            int itemCount = cart.RemoveFromCart(id);<br />
            // Display the confirmation message<br />
            var results = new ShoppingCartRemoveViewModel<br />
            {<br />
                Message = HtmlEncoder.Default.Encode(cartt.Album.Title) +<br />
            " has been removed from your shopping cart.",<br />
                CartTotal = cart.GetTotal(),<br />
                //CartCount = cart.GetCount(),<br />
                ItemCount = itemCount,<br />
                DeleteId = id<br />
            };<br />
            return Json(results);     <br />
        }</pre>



but it don't work and the text of the tags doesn't change and fadeOut() doesn't work.
Please help me to resolve my problem which I have been involved for several days


What I have tried:

in index.cshtml i use ajax in click event of .removelink to get changes from action controller, but this don't work 
Posted
Updated 13-Jan-20 22:55pm

The biggest help to solving your problem is going to be YOU and using the debuggers available to you to figure out where the breakdown is occurring. There are 2 separate debuggers you can be using:

1. Your browser has a debugger that can help you through javascript, network, and some other errors. You can access this by right-clicking on the page and choosing the "Inspect" option. The questions this can answer are available in the different panes
_a_ Are there errors in your javascript on a fresh page load?
_b_ Does an error occur when you press the button?
_d_ Is a network request made when the button is clicked?
_c_ What response code is returned (if any) when the button is clicked?

2. Visual Studio Debugger. Set up a breakpoint on your controller action and run the application in debug mode. use the F11 key to step through the action and see if all is working well.
That said, your AJAX call does have a success function defined but there are also functions that can be added for failures. I would look into leveraging this to get some feedback on any errors that are being returned
 
Share this answer
 
Comments
[no name] 12-Jan-20 16:28pm    
Thank you for your good guidance. When I send a unit field (eg, a string or an integer) Jason reads it well.
But when I send a class containing some properties (like the example above), its value in the data parameter is problematic.
MadMyche 12-Jan-20 19:22pm    
It looks like your controller action wants an integer to be sent to it
[no name] 14-Jan-20 5:00am    
I convert results to json type then send it.worked for me
i add The following code to convert data to json in RemoveFromCart controller action:
var resulTtoJson = Newtonsoft.Json.JsonConvert.SerializeObject(results);

and return json type :
[HttpPost]
        public IActionResult RemoveFromCart(int id)
        {
            //Remove the item from the cart
            var cart = ShoppingCart.GetCart(this.HttpContext);
            // Get the name of the album to display confirmation
            //string albumName = _context.Carts
            //.Single(item => item.RecordId == id).Album.Title;
            Cart cartt = ShoppingCart.getCartForGetalbumName(id);
            // Remove from cart
            int itemCount = cart.RemoveFromCart(id);
            // Display the confirmation message
            var results = new ShoppingCartRemoveViewModel
            {
                Message ="محصول"+ cartt.Album.Title +
            "از سبد خریدتان حذف گردید.",
                CartTotal = cart.GetTotal(),
                //CartCount = cart.GetCount(),
                ItemCount = itemCount,
                DeleteId = id
            };
           
            var resulTtoJson = Newtonsoft.Json.JsonConvert.SerializeObject(results);

            return Json(resulTtoJson);

also add the following code in view to convert data to javascript type:
var data =JSON.parse(dataa);

and use it:

$(".RemoveLink").click(function () {
                // Get the id from the link
                var recordToDelete = $(this).attr("data-id");
               // alert(recordToDelete);
                if (recordToDelete != '' || recordToDelete != null) {
                    // Perform the ajax post
                    $.post("/ShoppingCart/RemoveFromCart/", { id: recordToDelete},
                        function (dataa) {
                            // Successful requests get here
                            // Update the page elements
                                 var data =JSON.parse(dataa);

                            if (data.ItemCount == 0) {
                                $('#row-' + data.DeleteId).fadeOut('slow');
                            } else {
                                $('#item-count-' + data.DeleteId).text(data.ItemCount);
                            }
                            $('#cart-total').text(data.CartTotal);
                            $('#update-message').text(data.Message);
                            $('#cart-status').text('Cart (' + data.CartCount + ')');
}
                        });       
           
                }               
            });
 
Share this answer
 
v2
Comments
MadMyche 14-Jan-20 6:58am    
Please add this to your Original question, explaining that this is what made it work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900