HTML
<div class="fc-option-more-input">
<input type="number" id="itemCount">
<button type="submit" onclick="location.href='@Url.Action("AddToCart", "Controller", new { id = Model[i].ItemID, itemCount = ??? })'" class="button button-add-custom-qty" disabled="disabled">
<span>Add</span>
</button>
</div>
控制器
public ActionResult AddToCart(int id, int itemCount)
{
var ItemToAdd = db.Items
.Single(item => item.ItemID == id);
var cart = ShoppingCart.GetCart(this.HttpContext);
ItemVM model = new ItemVM();
model.ID = ItemToAdd.ItemID;
model.ItemName = ItemToAdd.ItemName;
model.ItemPrice = ItemToAdd.ItemPrice;
model.ImageURL = ItemToAdd.ImageUrl;
model.ItemPrice = ItemToAdd.ItemPrice * itemCount;
cart.AddToCart(model, itemCount);
return RedirectToAction("Index");
}
单击按钮时,我需要以某种方式读取输入元素的文本输入(数字)并将其发布到控制器。如何实现呢?
答案 0 :(得分:1)
或使用带有Razor代码的Form,如下所示:
<div class="fc-option-more-input">
@using (Html.BeginForm("AddToCart", "Controller", new { id = 0 }, FormMethod.Post))
{
<input type="number" id="itemCount" name="itemCount"/>
<button type="submit"><span>Add</span></button>
}
</div>
答案 1 :(得分:1)
为什么不使用模型来向控制器端提交表单
@model AddToCart
@using (Html.BeginForm("AddToCart", "Controller", FormMethod.Post))
{
@Html.HiddenFor(m => m.Id)
@Html.TextBoxFor(m => m.ItemCount )
<button type="submit"><span>Add</span></button>
}
</div>
public ActionResult AddToCart(AddToCart model)
{
var ItemToAdd = db.Items
.Single(item => item.ItemID == model.Id);
cart.AddToCart(model, model.ItemCount);
return RedirectToAction("Index");
}
public int Id {get;set;}
public int ItemCount {get;set;}
模型是类的一种,如果模型是另一个文件夹,则可以通过在cshtml文件中@model下方使用@进行引用 Id是您的商品ID,并在隐藏的页面中添加,以便在控制器端的模型中可用
答案 2 :(得分:0)
@using (Html.BeginForm("AddToCart", "ShoppingCart", new { id = Model[i].ItemID}, FormMethod.Post))
{
<div class="fc-option-more-input">
<input type="number" id="itemCount" name="itemCount">
<button type="submit" class="button button-add-custom-qty" disabled="disabled">
<span>Add</span>
</button>
}
</div>
这为我解决了。