Ajax POST到控制器动作以更新视图模型,然后重新加载div

时间:2015-10-06 16:49:47

标签: jquery ajax asp.net-mvc entity-framework ado.net

我使用ajax时仍然不稳定因此我的实现中存在一些漏洞。我试图发布一个控制器动作,它将调用存储过程来更新我的视图模型,然后重新加载将显示信息的div。

Ajax Post:

$("#order-summary-panel").click(function(){
    $.ajax({
        url: '@Url.Action("GetOrderSummary", "Home")',
        type: 'POST',
        success: function() {
          alert("It Worked!")
        }
    });
});

控制器操作:

[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 View("Index", viewModel)
    }
}

Div重新加载:

<div id="order-summary-panel">
    @if (Model != null && Model.OrderSummary != null)
    {
        foreach (var order in Model.OrderSummary)
        {
         // Display Orders
        }
    }
</div>

我相信我不应该返回完整视图,但我不确定如何在不这样做的情况下更新视图模型。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:8)

您可以返回PartialView并将结果放入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);
    }
}

并在您的javascript中:

$("#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

您还可以尝试返回json操纵html(可以提高性能),样本:

[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);
    }
}

在您的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
               }
            }
        }
    });
});