2013-02-15 50 views
0

我想在ASP.Net MVC 3應用程序中引發驗證錯誤。 當用戶輸入一個大於1000的數字時,應顯示錯誤消息。在視圖模型上使用下面的代碼,它似乎不工作。
我需要改變什麼?範圍驗證的文本框不工作在MVC3

[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

您的cshtml或aspx視圖是什麼樣的?你的控制器動作是什麼樣的? – Andorbal 2013-02-15 20:26:12

+1

您可能未檢查控制器中的ModelState ... – 2013-02-15 20:27:28

回答

1

您還需要顯示的驗證消息:

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

是否可以限制文本框中的字符數。 [例如:] – BumbleBee 2013-02-15 20:38:51

+0

@BumbleBee是的,只需使用[StringLength](http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations。 stringlengthattribute.aspx)屬性。 – 2013-02-15 20:43:14

+0

ValidationMessageFor()也不起作用。 – BumbleBee 2013-02-15 20:49:05

0

嘗試

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

我想,這個問題occures,becase的你的財產是int類型,範圍是int類型,BYT你是顯示在一個文本框它。

此外,您還需要在控制器中添加ModelState.IsValid。例如:

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

    return View(create) 
}