2010-04-17 65 views
1

我有一些看起来很简单的东西不工作。ModelState总是有效

我有一个模型

public class Name: Entity 
{ 
    [StringLength(10), Required] 
    public virtual string Title { get; set; } 
} 

public class Customer: Entity 
{ 
    public virtual Name Name { get; set; } 
} 

视图模型

public class CustomerViweModel 
{ 
    public Customer Customer { get; set; } 
} 

视图

 <% using(Html.BeginForm()) { %> 
        <%= Html.LabelFor(m => m.Customer.Name.Title)%> 
        <%= Html.TextBoxFor(m => m.Customer.Name.Title)%> 
        <button type="submit">Submit</button> 
     <% } %> 

和控制器

[HttpPost] 
public ActionResult Index([Bind(Prefix = "Customer")] Customer customer) 
{ 
     if(ModelState.IsValid) 
      Save 
     else 
      return View(); 
} 

无论我输入什么标题(null或字符串> 10个字符),ModelState.IsValid始终为true。 Customer对象中的Title字段有一个值,所以数据正在被传递,但未被验证?

任何线索?

回答

0

想通了,这是因为我引用System.ComponentModel.DataAnnotations 3.6而不是3.5。从我所了解的情况来看,3.6仅适用于WCF RIA服务。

5

在您的视图中,我看不到任何文本框或允许将数据发送到控制器的字段,只有一个标签。物业将not be validated if they are not posted。添加一个文本框,将其留空,你的模式将不再有效更:

<%= Html.TextBoxFor(m => m.Customer.Name.Title)%> 

UPDATE:

下面是我使用的代码:

型号:

public class Name 
{ 
    [StringLength(10), Required] 
    public virtual string Title { get; set; } 
} 

public class Customer 
{ 
    public virtual Name Name { get; set; } 
} 

public class CustomerViewModel 
{ 
    public Customer Customer { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index([Bind(Prefix = "Customer")]Customer cs) 
    { 
     return View(new CustomerViewModel 
     { 
      Customer = cs 
     }); 
    } 
} 

查看:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyApp.Models.CustomerViewModel>" %> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    <% using(Html.BeginForm()) { %> 
     <%= Html.LabelFor(m => m.Customer.Name.Title)%> 
     <%= Html.TextBoxFor(m => m.Customer.Name.Title)%> 
     <button type="submit">Submit</button> 
    <% } %> 
</asp:Content> 

当您提交此表显示验证错误。

备注1:我在模型中省略了Entity基类,因为我看起来不怎么样。

备注2:我已将Index操作中的变量重命名为cs。我记得在ASP.NET MVC 1.0中存在一些与前缀和变量名称相同的问题,但我不确定这是否适用于此,我认为它已修复。

+0

我的不好,我在视图中有一个文本框。 – 2010-04-17 17:08:45

+0

那么,我刚刚尝试过这个例子,它按预期工作,验证错误显示标题属性。 – 2010-04-17 17:10:21