9

我使用更新操作根据来自@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");
            }
4

1 回答 1

5

当您使用时,您的问题中有答案

@Html.TextBoxFor(modelItem => item.Quantity)
@Html.ValidationMessageFor(modelitem => item.Quantity)

您会收到错误消息,因为 MVC 模型验证适用于name属性,正如@Mystere Man 在评论中所说,您违反了所有约定和约定是 MVC 的全部内容,要么更改模型中的属性名称,要么将其用作它如果您想利用 MVC 的模型验证,则在视图中。


不完全相关,但很好读。

于 2012-10-23T05:39:46.640 回答