问题描述
||
我正在尝试为添加到购物车中的商品数量实施数量选择器。
我有一个带有动态名称的文本框,用于目录中的每一行。每行都有一个“添加到购物车”按钮。
如果我在文本框中输入所需的数量,然后单击\“添加到购物车\”按钮,则希望将所选项目的输入数量添加到我的购物车中。
将新数量添加到购物车数据库的控制器操作如下:
public ActionResult AddToCart(int productID,int quant)
{
repository.AddItemToOrder(productID,quant);
return RedirectToAction(\"Browse\");
}
我知道调用\“ Browse \”操作再次呈现页面不是最有效的方法。我会在以后解释。
我的问题是:如何使用两个参数调用此“ AddToCart”控制器动作?
我能够获得使用1参数的版本。在这种情况下,将删除上述控制器操作中的第二个参数quant。
我的观点是:
<input type=\"button\" onclick=\"document.location.href = \'<%: Url.Action(\"AddToCart\") %>\'+\'?productID=<%: item.ProductID %>\' \" value=\"Add to Cart\" />
在此有效的同时,我需要能够引用文本框中的数量。
我尝试了下一行在View中包含多个参数的行:
<input type=\"button\" onclick=\"document.location.href = \'<%: Url.Action(\"AddToCart\") %>\'+\'?productID=<%: item.ProductID %>\'+\'?quant=<%: item.ProductID %>\' \" value=\"Add to Cart\" />
分配给\“ quant \”的值与分配给\“ productID \”的值相同。我这样做只是为了让某些东西正常工作。一旦工作,我计划使用具有动态名称的文本框的值。 (我也需要一些帮助)
当我测试并单击该行的按钮时,收到以下错误:
参数字典包含\'OER中方法\'System.Web.Mvc.ActionResult AddToCart2(Int32,Int32)\'的非空类型\'System.Int32 \'的参数\'productID \'的空条目。 Controllers.eCommerceController \”。可选参数必须是引用类型,可为空的类型,或者必须声明为可选参数。
参数名称:参数
解决方法
您需要在查询字符串中的变量之间加上一个&符号
&
,而不是另一个?
...简单的错字。
/AddToCart?productId=3&quant=1
如果要给quant
一个默认值,因此并非总是需要此值,则可以将操作方法更改为:
public ActionResult AddToCart(int productID,int quant = 1)
根据您的评论,我将设置一个按钮将提交的表单,而不是将其全部压缩为onclick
:
@using(Html.BeginForm(\"AddToCart\")) {
@Html.Hidden(\"productId\",item.ProductId)
@Html.Input(\"quant\")
<input type=\"submit\" value=\"Add to Cart\" />
}
如果您只想切换到常规链接而不是按钮,则需要连接一些jQuery,以在单击时从文本框中提取quant
参数。
$(\'.addToCartLink\').click(function() { // All the \"add to cart\" links would have this class
// Pull the product ID (just an example)
var productId = $(this).attr(\'data-id\');
// Set the quantity
var quantity = $(\'#txtlinequantity-\'+productId).val();
// Possible validation here
...
// Hit the action method
window.location = \'/AddToCart?productId=\'+productId+\'&quant=\'+quantity;
});
, 你不要吗
<input type=\"button\" value=\"<%: item.ProductID %>\" name=\"productID\" id=\"productID\"/>
在您提交的表单中?
如果您要提交表单元素,则MVC将根据name
字段(或id
)自动提取所需的信息,并将其分配给代码中的等效变量。 “ 15”字段是分配给相应变量的值。