2010-07-13 36 views
0

我已經在我的aspx視圖頁面下面的代碼:MVC驗證不工作在Web窗體項目

<% using (Html.BeginForm()) 
    { 
%> 
<div> 
    CustomerCode:&nbsp; 
    <%= Html.TextBoxFor(x=> x.CustomerCode) %> 
    <%= Html.ValidationMessageFor(x => x.CustomerCode)%> 

這個代碼在我的模型:

public class MyModel 
{ 

    [Required(ErrorMessage="customer code req")] 
    [StringLength(2,ErrorMessage="must be 2 u idiot")] 
    public string CustomerCode {get; set;} 

但如果我輸入2個以上在文本框和charachters提交頁面,在控制器,當我做:

 if (ModelState.IsValid) 

它總是說,它有效嗎?我錯過了什麼?我已經把這個MVC項目放在一個Web Forms項目中,但是MVC項目工作正常,只是驗證不起作用,有什麼想法?謝謝。

回答

3

確保控制器行動接受模型參數:

public ActionResult SomeAction(MyModel model) 
{ 
    if (ModelState.IsValid) 
    { 

    } 
    return View(); 
} 

現在,如果你調用:

http://example.com/myapp/home/someaction?customercode=123 

模型不應該是有效的。

+0

感謝,但我已經這樣做了,它仍然說這是有效的,當它顯然不是! :( – Lisa 2010-07-13 13:55:40

0

嗯,它爲我的測試頁上,使用下列

public ActionResult Test() 
    { 
     MyModel model = new MyModel(); 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Test(MyModel model) 
    { 
     if (ModelState.IsValid) { } 
     return View(model); 
    } 

<% using (Html.BeginForm()) {%> 
    <%: Html.ValidationSummary(true) %> 

    <fieldset> 
     <legend>Fields</legend> 

     <div class="editor-label"> 
      <%: Html.LabelFor(model => model.CustomerCode) %> 
     </div> 
     <div class="editor-field"> 
      <%: Html.TextBoxFor(model => model.CustomerCode) %> 
      <%: Html.ValidationMessageFor(model => model.CustomerCode) %> 
     </div> 

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 

<% } %> 

public class MyModel 
{ 
    [Required(ErrorMessage = "customer code req")] 
    [StringLength(2, ErrorMessage = "must be 2 u idiot")] 
    public string CustomerCode { get; set; } 

} 
+0

是的,我嘗試了一個測試應用程序,它似乎工作得很好 - 我將這個新的mvc項目合併到現有的webform框架之上 - 你認爲我在web.config或global中可能錯過了一些東西asax ?? – Lisa 2010-07-13 14:15:11

+1

可能是值得檢查目標網站的框架版本。沒有什麼明顯的想法,我想這是你獲得報酬的原因之一:) – 2010-07-13 14:21:08

+0

嗨,謝謝你,但我認爲有一些衝突與我的structureMapController在全局asax文件(需要爲單元測試進行依賴注入)因此,最後,而不是使用DataAnnotations進行驗證,我使用了Microsoft Enterorise庫驗證,而不是最終的工作。 - 感謝大家試圖幫助,雖然:) – Lisa 2010-07-13 15:57:48