2010-07-13 34 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