In ASP.NET MVC, when you want to submit a page with many instances of a certain type (e.g., a form with a list of phone numbers), the framework will recognize the form elements as a list if you use a specific format for the name attribute of the inputs. This allows you to have an action like this:
public ActionResult UpdateInts(IList<int> ints) {
The MVC framework, in this case, will look at all the inputs on your form, figure out which inputs correspond to which records on the form, find each record individually, and pass the whole list to your action as an IList<T>. Pretty convenient, that.
Note that the format for the name element requires square brackets and a period.
<input type="text" name="products[0].Name" value="Beer" />
There is no way around this required formatting; it is hard-coded into the framework source code. (See DefaultModelBinder.cs.)
Unfortunately, these are special characters in jQuery selectors. As a result, some plug-ins can become unhappy when you use them in an input name. For example, the ClockPick plugin has an option which is useful when you want an image that the user can click on in order to pop up the clock picker instead of clicking on the input itself:
$(".clockpick").clockpick({ valuefield : 'myfieldname' });
If the name attribute of your input happens to be myfieldname, this works fine. If, on the other hand, it is products[0].Name, it doesn’t work at all.
The solution is to include an extra set of quotes around the name with the brackets and the dot:
$(".clockpick").clockpick({ valuefield : "'products[0].Name'" });
With only one set of quotes, we just have a string containing products[0].Name. With two sets of quotes, the string contains the same thing, except surrounded by quotes. This causes jQuery to not treat the square brackets and the dots as special characters. As the jQuery documentation notes:
Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]".
Post a Comment