数据注释不包括表单元素上的数据属性
我一定在这里遗漏了一些完全明显的东西。我刚刚开始一个干净的项目 - MVC 3/Razor - 我正在尝试配置不显眼的 JavaScript 验证。我能找到的所有内容都表明我只需将数据注释添加到我的模型中,并在 web.config 中将 UnobtrusiveJavaScriptEnabled 设置为 true,一切都应该正常。我遇到的问题是,当我查看渲染的源时,我的输入字段甚至没有 data-val 属性。这是我得到的:
public class PersonModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
在控制器中:
public ActionResult Index()
{
return View(new Models.PersonModel());
}
在视图中:
@model ValidationTest.Models.PersonModel
...
@Html.EditorFor(m => m.FirstName)
我希望看到包含 data-val 属性的输入标签,但我只看到:
<input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="">
我是否在某处缺少一个简单的设置?
I must be missing something totally obvious here. I just started with a clean project - MVC 3/Razor - and I'm attempting to configure unobtrusive JavaScript validation. Everything I can find says I just need to add the data annotations to my model, and set UnobtrusiveJavaScriptEnabled to true in the web.config, and everything should work. The problem I'm having is that when I look and the rendered source, my input field doesn't even have the data-val property. Here's what I've got:
public class PersonModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
And in the controller:
public ActionResult Index()
{
return View(new Models.PersonModel());
}
And in the View:
@model ValidationTest.Models.PersonModel
...
@Html.EditorFor(m => m.FirstName)
I would expect to see an input tag rendered that includes the data-val attribute, but instead I'm only seeing:
<input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="">
Am I missing a simple setting somewhere?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据实施情况:
仅当启用了不显眼的客户端验证时才渲染属性,并且仅当我们从未在此表单中为具有此名称的字段渲染验证时才渲染属性。另外,如果没有表单上下文,那么我们无法渲染属性(我们无法将它们附加到)。
所以我想你需要将 EditorFor 放入表单中
According to the implemetation:
Only render attributes if unobtrusive client-side validation is enabled, and then only if we've never rendered validation for a field with this name in this form. Also, if there's no form context, then we can't render the attributes (we'd have no to attach them to).
So I guess you need to put your EditorFor inside a Form