ASP.NET MVC - How to call void controller method without leaving the view?

前端 未结 7 2275
北恋
北恋 2020-12-01 11:51

Question background:

I am implementing some basic \'shopping cart\' logic to an MVC app. Currently when I click a link - denoted as \'Add T

7条回答
  •  渐次进展
    2020-12-01 12:44

    Basically @Html.ActionLink() or tag uses get request to locate the page. Hence whenever you clicked it, you request to your AddToCart action method in ProductController and if that action method returns null or void so a blank or empty page is shown as you experienced (because or @Html.ActionLink() get request by Default).

    So if you want to add your value to cart then call AddToCart method using ajax i.e:

    HTML:

    @Html.ActionLink("Add To Cart", "AddToCart", null, new { id="myLink"})
    

    Jquery or Javascript:

    $("#myLink").click(function(e){
    
        e.preventDefault();
        $.ajax({
    
            url:$(this).attr("href"), // comma here instead of semicolon   
            success: function(){
            alert("Value Added");  // or any other indication if you want to show
            }
    
        });
    
    });
    

    'AddToCart' method in the ProductController:

    public void AddToCart()
    {
       //Logic to add item to the cart.
    }
    

    Now this time when the call goes to AddToCart method it goes by using ajax hence the whole page will not redirect or change, but its an asynchronous call which execute the AddToCart action method in your ProductController and the current page will remains same. Hence the product will also added to cart and page will not change to blank.

    Hope this helps.

提交回复
热议问题