文本框的范围验证在MVC3中不起作用

时间:2013-02-15 20:25:03

标签: c# asp.net-mvc-3

我正在尝试在ASP.Net MVC 3应用程序中引发验证错误。  当用户输入大于1000的数字时,应显示错误消息。在视图模型上使用以下代码它似乎不起作用。
 我需要改变什么?

[Range(0, 1000, ErrorMessage = "Total number of rows to display must be between 0 to 1000")]
 public int DisplayTop { get; set; }

cshtml:

@model  Calc.Models.CountingVM
@{
    ViewBag.Title = "Reports";
    Layout = "~/Views/Shared/_reportsLayout.cshtml";
}
@using (Html.BeginForm("Reports", "Calc", FormMethod.Post, new { @id = "frmReport" }))
{   
 .........
  @Html.TextBoxFor(c => c.DisplayTop, "1000")
  @Html.ValidationMessageFor(c => c.DisplayTop)
}

行动方法:

       public ActionResult Reports(string ReportName, CalcCriteria criteria)
            {

                  if ((criteria == null) || (criteria.nId == null))
                    {
                        criteria = TempData["criteria"] as CalcCriteria;
                        TempData["criteria"] = criteria; // For reload, without this reloading the page causes null criteria.
                    }
                  ReportType c = (ReportType)Enum.Parse(typeof(ReportType), ReportName, true);
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    string vmJson = string.Empty;

                    switch (c)
                    {
                           .....
                            int displayTop;
                           ..........
                            case ReportType.Inventory_Counts_Report:                      
                           ..............
                            displayTop = Convert.ToInt32(Request["DisplayTop"]);
                           ........
                     return View("Counting", CountingVM);
                     default:
                            return View();
                     }
                return View(); }

谢谢

BB

2 个答案:

答案 0 :(得分:1)

您还需要显示验证消息:

@Html.ValidationMessageFor(c => c.DisplayTop)

答案 1 :(得分:0)

尝试

@Html.EditorFor(c => c.DisplayTop, "1000")

我猜,问题发生了,因为你的属性是int类型,范围是int类型,你是在文本框中显示它。

您还需要在控制器中添加ModelState.IsValid。例如:

[HttpPost]
public ActionResult Create(YourModel model)
{
   if(ModelState.IsValid)
   {
      // Put your logic here
   }

   return View(create)
}