我正在更新产品数量按更新按钮,点击更新按钮页面后重新加载,而不是重新加载该页面我想只通过Ajax更新“cartUpdatePanel”表区域
我的观点是
using (Html.BeginRouteForm("ShoppingCart", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table id="cartUpdatePanel" class="table_class" cellpadding="0" cellspacing="0">
@foreach (var item in Model.Items)
{
<tr style="background: #f3f3f3;">
<td>
<input type="submit" name="updatecartproduct@(item.Id)" value="Update Cart" id="updatecartproduct@(item.Id)" />
</td>
</tr>
}
}
我的控制器操作是,我正在更新产品数量
[ValidateInput(false)]
[HttpPost, ActionName("Cart")]
[FormValueRequired(FormValueRequirement.StartsWith, "updatecartproduct")]
public ActionResult UpdateCartProduct(FormCollection form)
{
if (!_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart))
return RedirectToRoute("HomePage");
//get shopping cart item identifier
int sciId = 0;
foreach (var formValue in form.AllKeys)
if (formValue.StartsWith("updatecartproduct", StringComparison.InvariantCultureIgnoreCase))
{
sciId = Convert.ToInt32(formValue.Substring("updatecartproduct".Length));
break;
}
//get shopping cart item
var cart = _workContext.CurrentCustomer.ShoppingCartItems
.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
var sci = cart.Where(x => x.Id == sciId).FirstOrDefault();
if (sci == null)
{
return RedirectToRoute("ShoppingCart");
}
//update the cart item
var warnings = new List<string>();
foreach (string formKey in form.AllKeys)
if (formKey.Equals(string.Format("itemquantity{0}", sci.Id), StringComparison.InvariantCultureIgnoreCase))
{
int newQuantity = sci.Quantity;
if (int.TryParse(form[formKey], out newQuantity))
{
warnings.AddRange(_shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,
sci.Id, newQuantity, true));
}
break;
}
//updated cart
cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
var model = PrepareShoppingCartModel(new ShoppingCartModel(), cart, true, false, true);
//update current warnings
//find model
var sciModel = model.Items.Where(x => x.Id == sciId).FirstOrDefault();
if (sciModel != null)
foreach (var w in warnings)
if (!sciModel.Warnings.Contains(w))
sciModel.Warnings.Add(w);
return View(model);
}
如何通过ajax点击更新按钮后更新“cartUpdatePanel”表区域
Thanx提前
答案 0 :(得分:1)
请考虑使用Ajax.BeginForm帮助程序来创建表单。您可以使用AjaxOptions指定回调代码来捕获服务器输出并执行您想要的任何操作(包括将其注入div,表,字段集......)
使用Ajax.BeginForm非常简单
@using (Ajax.BeginForm(
"name_of_the_action",
new AjaxOptions {
OnSuccess = "processServerResp",
HttpMethod = "POST"},
new {enctype="multipart/form-data"})
){
// rest of the form code
}
现在使用javascript,将processServerResp实现为一个带有单个参数的函数。此参数将包含从服务器传递到客户端的值。假设服务器返回html,您可以使用以下代码将其注入ID为id_fo_the_div
的容器中function processServerResp(serverData){
$(‘#id_fo_the_div’).html(serverData);
// or inject into a table ..
}
您可以使用AjaxOptions提供的其他有趣功能,并做一些非常有趣的事情。
关于Ahax.BeginForm http://www.blackbeltcoder.com/Articles/script/using-ajax-beginform-with-asp-net-mvc
的好文章快乐编码