我是MVC的新手
我需要一些帮助来解决在表单提交
上将参数传递给控制器的问题我得到的是以下控制器和视图
public ActionResult Index(string method ="None")
{
if (Request.HttpMethod == "POST")
{
switch (method)
{
case "Add10":
_bag.GetBag = Get100Products().Take(10).ToList<Product>();
break;
case "Clear":
_bag = null;
_bag.GetBag = null;
_bag = new Models.Bag();
break;
case "Add":
if ((Request.Form["Id"] != null) && (Request.Form["Id"] != ""))
{
if (_bag.GetBag.Count < 100)
{
var p = GetProduct(Request.Form["Id"]);
int qnt = Convert.ToInt16(Request.Form["qnt"]);
if (p.ItemNumber != null)
{
p.Quantity = qnt;
p.Index++;
_bag.Item = p;
}
}
}
break;
}
}
return View(_bag.GetBag);
}
和视图的视图部分
<div style="vertical-align:middle">
@using (Html.BeginForm("", "Home", new { method = "Add10" }, FormMethod.Post))
{
<!-- form goes here -->
<input type="submit" value="Add 10 Items to bag" />
}
@using (Html.BeginForm("GetDiscount", "Home", FormMethod.Post))
{
<div>
<!-- form goes here -->
<input type="submit" value="Get Discount" />
With MAX time in seconds <input type="text" name="time" maxlength="2" value="2" />
</div>
}
@using (Html.BeginForm("", "Home", new { method = "Clear" }, FormMethod.Post))
{
<input type="submit" value="Empty the bag" />
}
</div>
所以我期待当使用点击按钮添加10项到包以将方法值“Add10”传递给索引控制器并单击时清空包以通过“清除”索引控制器中的方法值
但它始终显示为“无”
我做错了什么?
</form>
答案 0 :(得分:0)
首先,您必须将[HttpPost]
添加到控制器才能接受POST请求:
[HttpPost]
public ActionResult Index(string method ="None")
{
答案 1 :(得分:0)
您应该区分GET和POST操作。
你可以这样做:
// [HttpGet] by default
public ActionResult Index(Bag bag = null)
{
// "bag" is by default null, it only has a value when called from IndexPOST action.
return View(bag);
}
[HttpPost]
public ActionResult Index(string method)
{
// Your logic as specified in your question
return Index(_bag.GetBag);
}
修改强>
您的代码错误,例如,您将获得NullReferenceException
,因为您尝试在空对象(_bag
)上调用属性:
_bag = null;
_bag.GetBag = null; // NullReferenceException: _bag is null!
如果我们将此Action
拆分为多个操作并遵循技术理念,您的代码也会更清晰,更易于维护。
您是否考虑将这段代码重构为更小,更易理解的块?