JQuery Validator plus Element IDs, and Names
OK, just discovered an interesting implementation detail of JQuery Validator (one that I should have known about already as well).
OK, if you have a form where the inputs of the for have both id and name attributes, the name attributes trump id.
So if you have this:
1: <input type='type' id='RegisterUserName' name='userName' />
Then you write the validation against ‘user’Name’, not ‘RegisterUserName’.
1: $("RegisterForm").validate({
2: rules: { userName: {required: true} }
3: });
If you do not you will get all sorts of strange null exception errors (which in JavaScript means something returned as ‘undefined’.
How this happens
People have been talking about the great flexibility of Asp.Net MVC for a while now, but there are a few things to be aware of. One of them is multiple forms.
Say you have a web page that has two forms on it, one to register users, the other to log users in. Both forms have ‘username’ and ‘password’ fields. Asp.Net MVC still cannot get you around the need to keep ids unique – but names can be reused. These names are also read by Asp.Net Action Controllers. So if you have multiple forms all submitting to the same Controller Action, as long as the name attributes are set it will hook up.
Anyway, this is a short post, mostly for myself, so I don’t spend two hours figuring this out again.
To reinforce your point, the key distinction is that form elements have an ID that represents them client-side, and each of those elements has two attributes sent to the server in a form submission: name & value. Unless you need to manipulate them client-side, you don’t need IDs on your form elements (I think the MVC TextBox helper renders an ID automatically, which it really shouldn’t do since they’re not required).
Actually, the ID is very useful and should always be present as that’s what you use to hook your [label] tags to their inputs.
I am with Richard on this one, as I typically have to assign labels to my inputs.
Side note: NEVER give your submit button an ID of ‘submit’. You just don’t want to go there.