ASP MVC + AJAX, trying to Update a div asynchronou

2019-06-27 11:48发布

问题:


I'm new to Asp MVC, and I'm trying to accomplish a little async update (I'm using MVC3 RC2, with Razor, but I can manage with ASPX solutions too).

I have a Master page, which renders a shopping cart box on every page by calling Html.RenderAction("Cart","Shop"). The Cart action of the ShopController calls the database, etc, and outputs the results. This works.
First problem: if I put an ActionLink in this partial view (like Html.ActionLink("Remove")), then even if I call PartialView() from the Remove action, it renders only the shopping cart, and nothing else (in essence, my page disappears).
Second problem: There is a div called "cartContent" inside this partial view. I want to be able to put a link ANYWHERE (not just on the Master page or in the partial view), which when pressed calls a controller Action, and then updates ONLY the cartContent div based on the results. I've tried Ajax.ActionLink but it does the same as Html.ActionLink, even though I imported the Microsoft.MvcAjax js libs.
Also, if I solve the first problem, I want that to be async as well.

What solution do I use? I've tried setting UpdateTargetID to "cartContent", I've tried wrapping the cartContent into an Ajax.BeginForm, nothing. Do I HAVE to use jQuery (which I know nothing of)? Do I serialize some response to JSON, and update the div manually in Javascript? (I'm not really good at JS, I'm coming from the C# side of things)

回答1:

You put a link wherever you want:

@Html.ActionLink("remove item", "remove", "somecontroller", 
    new { id = Model.Id }, new { @class = "remove" })

And then in a separate javascript file:

$(function() {
    $('.remove').click(function() {
        // when the link is clicked
        // perform an ajax request:
        $.ajax({
            url: this.href,
            type: 'delete',
            success: function(result) {
                // when the AJAX call succeed do something with the result
                // for example if the controller action returned a partial
                // then you could show this partial in some div
                $('#someDivId').html(result);
            }
        });

        // don't forget to cancel the default action by returning false
        return false;
    });
});

Remark: if the div you are updating contains also the link then you might need to use the .live() function or the click event handler will not work the second time because the DOM will be modified:

$('.remove').live('click', function() {  
     ...
});