【问题标题】:How to make an Ajax Post Back with ASP.net MVC如何使用 ASP.net MVC 进行 Ajax 回传
【发布时间】:2013-09-04 06:40:30
【问题描述】:

我对 MVC 很陌生。所以,一直在研究CodePlex中MusicStore Application的代码。

我无法理解以下代码的含义:

 // AJAX: /ShoppingCart/RemoveFromCart/5

        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            // Remove the item from the cart
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Get the name of the album to display confirmation
            string albumName = storeDB.Carts
                .Single(item => item.RecordId == id).Album.Title;

            // Remove from cart
            int itemCount = cart.RemoveFromCart(id);

            // Display the confirmation message
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(albumName) +
                    " has been removed from your shopping cart.",
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                ItemCount = itemCount,
                DeleteId = id
            };

            return Json(results);
        }

        //
        // GET: /ShoppingCart/CartSummary

        [ChildActionOnly]
        public ActionResult CartSummary()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);

            ViewData["CartCount"] = cart.GetCount();

            return PartialView("CartSummary");
        }
    }
}

请帮我澄清一下,那个特殊的 HttpPost 是如何作为 Ajax Post 工作的。

【问题讨论】:

    标签: c# ajax asp.net-mvc http-post partial-views


    【解决方案1】:

    我知道这是一个老问题,但我在搜索中遇到了它,为了让它发挥作用,我必须在 Url.Action 周围添加引号。

    $.ajax({
          type: "POST",
          url: "@(Url.Action("RemoveFromCart"))",
          data: ({
                    Id:1
                 }),
          success: success,
          dataType: dataType
        })
    

    【讨论】:

      【解决方案2】:

      您好,您可以使用 jQuery Ajax 发出异步回发请求

      请看下面的代码

      $.ajax({
        type: "POST",
        url: @Url.Action("RemoveFromCart"),
        data: ({
                  Id:1
               }),
        success: success,
        dataType: dataType
      })
      

      [HttpPost] -- 属性确保 RemoveFromCart 操作方法只接受发布请求

      [ChildActionOnly] -- 属性确保动作方法只能作为视图中的子方法调用。这些通常与部分视图相关联。

      【讨论】:

      • 哪个视图引擎更适合使用 Razor 或 Aspx ? ASPX 视图引擎的局部视图使用什么控件
      • 嗨 Avinash,如果我们考虑一些小事,Razor 比 ASPX 更好。
      猜你喜欢
      • 2015-12-23
      • 2014-08-16
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 2010-10-09
      • 2011-04-22
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多