在MVC4中验证@ Html.Textbox

kk1*_*076 9 c# asp.net asp.net-mvc asp.net-mvc-3

我使用更新操作根据@ 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" />
   }
Run Code Online (Sandbox Code Playgroud)

在我的模型课中

        [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; }
Run Code Online (Sandbox Code Playgroud)

问题是当文本框为空时我没有收到验证消息.但是当我使用@ Html.TextBoxFor时

   @Html.TextBoxFor(modelItem => item.Quantity)
   @Html.ValidationMessageFor(modelitem => item.Quantity) 
Run Code Online (Sandbox Code Playgroud)


我收到验证消息.我的更新操作无效.
在这里,我有两个选择.
1.如何在@ Html.TextboxFor中传递文本框名称"qty"?(或)
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");
            }
Run Code Online (Sandbox Code Playgroud)

Raf*_*fay 5

当你使用时,你的答案就在你的问题中

@Html.TextBoxFor(modelItem => item.Quantity)
@Html.ValidationMessageFor(modelitem => item.Quantity)
Run Code Online (Sandbox Code Playgroud)

你得到错误消息因为MVC模型验证对name属性起作用@Mystere Man在评论中说你违反了所有的约定和惯例是MVC的全部内容,要么改变模型中的属性名称,要么使用它作为它如果您想利用MVC的模型验证,则在视图中.


不完全相关,但读得很好.