简体   繁体   English

如何使用ASP.net MVC进行Ajax回发

[英]How to make an Ajax Post Back with ASP.net MVC

I am very new to MVC . 我对MVC非常陌生。 So , have been studying the code of MusicStore Application in CodePlex. 因此,一直在研究CodePlex中MusicStore Application的代码。

I am unable to understand what does the following code meant: 我无法理解以下代码的含义:

 // 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");
        }
    }
}

Please help me clarify , how that particluar HttpPost works as a Ajax Post back . 请帮助我澄清一下,该特定的HttpPost是如何作为Ajax Post返回的。

I know this is an old question but I came across it in my searches and to get this to work I had to add quotes around the Url.Action. 我知道这是一个老问题,但是我在搜索中遇到了这个问题,为了使它起作用,我不得不在Url.Action周围添加引号。

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

Hi you can use jQuery Ajax to make an asynchronous postback request 嗨,您可以使用jQuery Ajax发出异步回发请求

please see the code below 请参见下面的代码

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

[HttpPost] -- attribute ensures that RemoveFromCart action method accepts only post requests [HttpPost] -属性确保RemoveFromCart操作方法仅接受发布请求

[ChildActionOnly] -- attribute ensures that an action method can be called only as a child method from within a view. [ChildActionOnly] -属性确保操作方法只能在视图中作为子方法调用。 These are typically associated with partial views. 这些通常与局部视图关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM