0

I have a view tied with a Item model that displays a shopping item. I want to a add a quantity text field and submit the itemID and quantity to a controller. I am using an AJAX form.

AJAX form:

@using (Ajax.BeginForm("AddToCart", "PizzaBasket",
new AjaxOptions
{
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "GET",
    OnFailure = "searchFailed",
    LoadingElementId = "ajax-loader",
    UpdateTargetId = "basketSummary",
})) 
{
@Html.HiddenFor(id => id.ItemId, new { @class = "id" })
<input type="hidden" name="id" class="id")/>
<label for="quantity">Quantity</label>
<input type="text" name="quantity" size="5"/>
<input type="submit" value="Add to Cart" />
<img id="ajax-loader" src="@Url.Content("~/Content/Images/ajax-loader.gif")" style="display:none"/> 
}

Controller action:

 public ActionResult AddToCart(String id, String quantity) {
 /*Add to cart*/
 return RedirectToAction("Index");           
} 

However, the id value is not getting submitted. Need to find out how to pass the id value from the AJAX form to the controller. Please note, that in the same file @Model.itemId is working fine.

4

3 回答 3

0

这一行:

@Html.HiddenFor(id => id.ItemId, new { @class = "id" })

需要在您的 Using 语句中。您的提交按钮/输入也是如此。为了使 ajax 表单正确提交,这两个必须在 Using 块内。

于 2013-08-18T02:49:50.340 回答
0

这是将发布id到您的控制器的控件(并注意括号,它应该被删除):

<input type="hidden" name="id" class="id") />

模型绑定器将使用此控件来填充String id控制器操作中的参数。由于您正在对其进行硬编码,因此在发布到控制器之前操纵其值的唯一方法是使用 javascript。你确定你正在这样做吗?否则,该值将显示为空。

此外,对于您的 Ajax 选项,您应该将方法设置为发布:

HttpMethod = "POST"

我看不到您的特定控制器操作所期望的 HTML 操作,但我猜它已经被装饰了[HttpPost]

于 2013-08-18T11:23:18.137 回答
0

您可以按如下方式使用表单集合,

看法 :

@Html.HiddenFor(m=>m.ProductID)

控制器:

    [HttpPost]
    public void HiddenForExample(FormCollection collection)
    {
        string productid = Convert.ToString(collection["ProductID"]);
    }
于 2013-08-18T08:23:21.967 回答