Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

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

Question background:

I am implementing some basic 'shopping cart' logic to an MVC app. Currently when I click a link - denoted as 'Add To Cart' on the screen shot below this calls to an 'AddToCart' method in the 'ProductController' as shown:

enter image description here

Product.cshtml code:

@Html.ActionLink("Add To Cart", "AddToCart")

'AddToCart' method in the ProductController:

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

The issue:

Not an issue as such but currently when I click the 'Add To Cart' button on the ActionLink on the ProductDetail.cshtml view the page calls the 'AddToCart' method on the ProductController and gives a blank view on the page - as shown below. I want the view to stay on 'ProductDetail.cshtml' and just call the 'AddToCart' method, how do I do this?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically @Html.ActionLink() or <a></a> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...