【发布时间】:2012-10-23 05:21:03
【问题描述】:
我使用更新操作根据来自@Html.Textbox 的输入进行更新。
@using (Html.BeginForm("Update", "Shopping", new { UserID = Request.QueryString["UserID"] }, FormMethod.Post, new { id = "myForm" }))
{
@Html.ValidationSummary()
@Html.Hidden("id", @Request.QueryString["UserID"] as string)
@Html.Hidden("productid", item.ProductID as string)
@Html.TextBox("Quantity", item.Quantity)
@Html.ValidationMessage("Quantity", "*")
@Html.Hidden("unitrate", item.Rate)
<input type="submit" value="Update" />
}
在我的模型类中
[Required(ErrorMessage = "Quantity is required.")]
[Display(Name = "Quantity")]
[Range(2, 100, ErrorMessage = "There is not enough inventory for the product to fulfill your order.")]
public int? Quantity { get; set; }
问题是当文本框为空时我没有收到验证消息。 但是当我使用@Html.TextBoxFor
@Html.TextBoxFor(modelItem => item.Quantity)
@Html.ValidationMessageFor(modelitem => item.Quantity)
我收到验证消息。我的更新操作不起作用。
在这里,我有两个选择。
1. 如何在@Html.TextboxFor 中传递文本框名称“数量”?? (或者)
2.如何使用@Html.ValidationMessage()获取@Html.Textbox()中的验证信息
任何建议..
编辑:
我的更新操作
[HttpPost]
public ActionResult Update(string id, string productid, int Quantity, decimal unitrate)
{
if (ModelState.IsValid)
{
int _records = UpdatePrice(id, productid, Quantity, unitrate);
if (_records > 0)
{
return RedirectToAction("Index1", "Shopping", new { UserID = Request.QueryString["UserID"] });
}
else
{
ModelState.AddModelError("","Can Not Update");
}
}
return View("Index1");
}
【问题讨论】:
-
这在很多方面都是错误的。您基本上打破了 MVC 的所有约定,并期望它仍然有效。 MVC 要求将文本框命名为与您正在验证的属性相同的名称。通过将文本框命名为
Quantity,您可以在 Html.TextBox 中获得验证消息。 -
我什至尝试在文本框中给出确切的名称“数量”。但不会出现验证消息。相反,我收到这样的消息。”参数字典包含一个空条目,用于控制器中方法的不可为空类型“System.Int32”的参数“数量””
-
可能有很多原因,但您没有提供足够的上下文来了解它们是什么。您的 Quantity 是否在视图模型的嵌套对象中?当您使用 TextBoxFor 方法时,查看网页呈现时的源代码并查看文本框的 Name 属性。尝试将其命名为“item.Quantity”。
-
那么,当您的 Update 方法采用 Quantity 时,您为什么要尝试传递 qty?
-
Yes.Quantity 是我模型中的嵌套对象。当我传入 @Html.TextboxFor() 时,我得到了 item.Quantity 作为名称
标签: c# asp.net asp.net-mvc asp.net-mvc-3