ASP MVC + AJAX trying to update div asynchronously


I am new to Asp MVC and I am trying to do a small async update (I am using MVC3 RC2 with Razor, but I can deal with ASPX solutions too).

I have a Master page that displays a cart on each page, calling Html.RenderAction ("Cart", "Shop"). The Cart ShopController action invokes the database, etc. And displays the results. It works.
First problem: if I put ActionLink in this partial view (for example, Html.ActionLink ("Delete")), then even if I call PartialView () from the "Delete" action, it will only display the shopping cart, and nothing else (by essentially, my page disappears).
Second problem: In this partial view, there is a div called "cartContent". I want to be able to place the ANYWHERE link (not only on the main page or in a partial view), which, when clicked, triggers a controller action and then updates the cartContent element ONLY based on the results. I tried Ajax.ActionLink, but it does the same as Html.ActionLink, although I imported Microsoft.MvcAjax js files.
Also, if I solve the first problem, I want it to be asynchronous as well.

What solution am I using? I tried setting UpdateTargetID to "cartContent", I tried wrapping cartContent in Ajax.BeginForm, nothing. Should I use jQuery (which I know nothing about)? Am I serializing some JSON response and updating the div manually in Javascript? (I'm not very good at JS, I am coming from C #)

+4
source share
1 answer

You put the link where 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; }); }); 

Note: if the updated div also contains a link, you may need to use the .live() function or the click event handler will not work a second time, since the DOM will be changed:

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

Source: https://habr.com/ru/post/1332708/


All Articles