How to update / reload partial view from main view in MVC

I am showing a partial view (cart) inside my main (pricing view) using RenderAction

<% Html.RenderAction("Cart", "ShoppingCart"); %>

When the user adds items to the cart on the main view, I must update the partial view to display the new items. Here is the code for my view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Trl.ViewModels.Cart>" %>
<% foreach (var _hotel in Model.Hotels)
   { %>
   Hotel Name: <%: _hotel.Name %> <br/>
   Price: <%: _hotel.TotalPrice %>
<% } %>

The Trl.ViewModels.Cart object used in the user control will contain the new elements as I use ASP.NET session state to save the recycle bin. How to update / reload this partial view from my main view so that it can display new elements?

+5
source share
1 answer

ok, (-) , .

, ajax. , , ajax , , . , div, , .

, , :

:

public ActionResult Create(Cart item)
{
    if (ModelState.IsValid)
    {
        // or could be added to session["cart"] etc..
        _repository.Add(item);
        var cartItems = _repository.Find(x => x.cartID = item.cartID);
        return PartialView("CartMini", cartItems);
    }
    return new EmptyResult();
}

( - , ):

<div id="miniCart"></div>

(semi psuedo-code):

<script type="text/javascript">
     function updateCart() {
         var tdata = $(frm).serialize(); 
         // or your data in the format that will be used ??
         $.ajax({
           type: "POST",
           data: tdata,
           url : '<%= Url.Action("Create", "Cart") %>',
           dataType: "json",
           success: function (result) { success(result); }  
        });
      }); 

    function success(result){
        $("#miniCart").html(result);
    }
</script>

, . , , , :). , .

+16

All Articles