2

我有一些看似非常简单的东西不起作用。

我有一个模型

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 始终为真。Customer 对象中的 Title 字段有一个值,所以数据正在传递,但没有被验证?

有什么线索吗?

4

2 回答 2

5

在您的视图中,我看不到任何允许向控制器发送数据的文本框或字段,只有一个标签。如果未发布属性,则不会对其进行验证。添加一个文本框,将其留空,您的模型将不再有效:

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

更新:

这是我使用的代码:

模型:

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>

当您提交此表单时,会显示验证错误。

Remark1:我Entity在模型中省略了基类,因为我不知道它看起来如何。

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

于 2010-04-17T16:45:05.547 回答
0

想通了,这是因为我引用 System.ComponentModel.DataAnnotations 3.6 而不是 3.5。据我所知,3.6 仅适用于 WCF RIA 服务。

于 2010-04-18T09:48:32.943 回答