开发者

Client-Side Validation and Collections or Dynamic Forms

开发者 https://www.devze.com 2022-12-16 09:00 出处:网络
I\'m using ASP.NET MVC 2.0. I need to implement a dynamic form in order to add \"on the fly\" new form开发者_如何学JAVA table row.

I'm using ASP.NET MVC 2.0.

I need to implement a dynamic form in order to add "on the fly" new form开发者_如何学JAVA table row.

My ViewModel contains an ICollection according to each rows which will be added to the form.

Now how can i make client side validation with that mechanism ?


You should bind your model to the list.

Please look at the: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx (Phil Haack is one of the Microsoft MVC people). This is basically a hack Microsoft guys made to allow for the functionality (Phill claims that they are designing some other way of doing this, but for now this is how we do it). You can easily add a validation control to this. Please look VERY carefully when you implement the naming scheme, and do NOT forget to put the hidden 'Index' field. Value of index can be anything you like (it doesn't have to be numbers in the sequence) but whatever you put in the hidden field as a value has to be within the square brackets for input controls that follow, just like in the Phill's example. Double check it, I once came to the point of pure misery because I forgot to put the hidden Index, as it is very easy to miss something. Also, the second part of the naming scheme ('Name' and 'Price') has to be the same as in your model.

When you're done with that, use jQuery to dynamically add/remove items on your form. Please note that jQuery selector prevent you from using square brackets for id's, so you can construct 'id' attributes of the input controls in some other way (i.e. 'something_index_propertyName') while you keep the 'value' attribute according to the naming scheme.

Happy coding.

0

精彩评论

暂无评论...
验证码 换一张
取 消