Ajax POST to controller action to update view model, and then reload div

ado.net ajax asp.net-mvc entity-framework jquery

Accepted Answer

You might, for instance, return a PartialView and place the output in a div.

PartialView

[HttpPost]
public ActionResult GetOrderSummary
{
    using (var entity = new OrderEntities())
    {
         var user = User.Identity.Name;
         var orderSummary = entity.uspGetOrderSummary(user).ToList();
         var viewModel = new OrderViewModel
         {
             OrderSummary = orderSummary
         };

         return PartialView("Index", viewModel);
    }
}

likewise in your java script:

$("#order-summary-panel").click(function(){
    $.ajax({
        url: '@Url.Action("GetOrderSummary", "Home")',
        type: 'POST',
        success: function(data) {
            if (data) {  // check if data is defined
               $("#order-summary-panel").html(data);
            }
        }
    });
});

Json

You might also attempt to return ajson an HTML manipulation (which can boost efficiency), for illustration:

[HttpPost]
public ActionResult GetOrderSummary
{
    using (var entity = new OrderEntities())
    {
         var user = User.Identity.Name;
         var orderSummary = entity.uspGetOrderSummary(user).ToList();
         var viewModel = new OrderViewModel
         {
             OrderSummary = orderSummary
         };

         return Json(new { success = true, order = viewModel }, JsonRequestBehavior.DenyGet);
    }
}

Additionally, you might try reading these attributes in your Javascript:

$("#order-summary-panel").click(function(){
    $.ajax({
        url: '@Url.Action("GetOrderSummary", "Home")',
        type: 'POST',
        success: function(data) {
            if (data) {  // check if data is defined
               if (data.success) { // if success is true
                   alert("It Worked!"); 
                   // you could read data.order
               }
            }
        }
    });
});
8
10/6/2015 4:59:13 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow