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();
}
无论我输入什么作为标题(空,或字符串 > 10 个字符),ModelState.IsValid 始终为 true。 Customer 对象中的 Title 字段有一个值,因此数据正在传递,但没有经过验证?
有什么线索吗?
I've got something seemingly very simple not working.
I have got a model
public class Name: Entity
{
[StringLength(10), Required]
public virtual string Title { get; set; }
}
public class Customer: Entity
{
public virtual Name Name { get; set; }
}
a view model
public class CustomerViweModel
{
public Customer Customer { get; set; }
}
a view
<% using(Html.BeginForm()) { %>
<%= Html.LabelFor(m => m.Customer.Name.Title)%>
<%= Html.TextBoxFor(m => m.Customer.Name.Title)%>
<button type="submit">Submit</button>
<% } %>
and a controller
[HttpPost]
public ActionResult Index([Bind(Prefix = "Customer")] Customer customer)
{
if(ModelState.IsValid)
Save
else
return View();
}
No matter what I enter as the title (null, or a string > 10 chars), ModelState.IsValid is always true. The Title field in the Customer object has a value, so the data is being passed around, but not being validated?
Any clues?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的视图中,我没有看到任何文本框或允许将数据发送到控制器的字段,只有一个标签。属性将不会如果未发布,则进行验证。添加一个文本框,将其留空,您的模型将不再有效:
更新:
这是我使用的代码:
模型:
控制器:
视图:
当您提交此表单时,会显示验证错误。
备注1:我省略了模型中的 Entity 基类,因为我不知道它看起来如何。
备注2:我已将 Index 操作中的变量重命名为
cs
。我记得在 ASP.NET MVC 1.0 中,当前缀和变量命名相同时,会出现一些问题,但我不确定这是否适用于此,我认为它已修复。In your View I don't see any text box or a field allowing to send data to the controller, only a label. Properties will not be validated if they are not posted. Add a textbox, leave it blank and your model won't be valid any more:
UPDATE:
Here's the code I've used:
Model:
Controller:
View:
When you submit this form a validation error is shown.
Remark1: I've omitted the
Entity
base class in the models as I don't how does it look.Remark2: I've renamed the variable in the Index action to
cs
. I remember that there was some problems with this in ASP.NET MVC 1.0 when you had the prefix and the variable named the same but I am not sure whether this applies here and I think it was fixed.弄清楚了,这是因为我引用的是 System.ComponentModel.DataAnnotations 3.6 而不是 3.5。据我所知,3.6 仅适用于 WCF RIA 服务。
Figured it out, it was becuase I'm referencing System.ComponentModel.DataAnnotations 3.6 instead of 3.5. From what I gather, 3.6 is for WCF RIA services only.