ASP.NET MVC 2 client-side validation rules not being created

允我心安 提交于 2019-12-04 14:52:45

About five seconds after I posted the question, I realized something: My view didn't have ValidationMessage placeholders anywhere. I added <%= Html.ValidationMessageFor(model => model.Item.Name) %> and lo and behold, MVC added validation rules for Item.Name to the JS block at the bottom of the page.

It turns out that MVC does not emit client-side validation rules for a field unless you actually do one of the following:

  1. Call Html.ValidationMessage() for the property.
  2. Call Html.Validate() for the property. (This one won't output error messages)
  3. Render the controls using Html.EditorForModel(). (source)

Doing any of these tells MVC, "This property of my viewmodel is editable by the user, so you should be validating it." Just using the HTML helper to stick a textbox on the page -- even if you're using the new strongly-typed helpers -- isn't enough.

Dave Swersky

I have had no luck getting this to work in MVC 2 RC. According to other questions here on SO, you have to get the MicrosoftMvcJQueryValidation.js file from the MVC Futures release, hold your left foot behind your head, and whistle Dixie for half an hour. I did this and more and have not been able to make it work.

Hopefully it will be fixed in RTM.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!