I am using a strongly typed view that lists an enumeration of objects, something like this:
@model IEnumerable<Foo>
<table>
<tbody>
@Html.EditorForModel()
</tbody>
</table>
Let's say Foo
has a simple numeric property that I want to validate on the client side:
public class Foo
{
[Required]
public int Bar { get; set; }
}
Now the editor template for this object looks like this:
@model Foo
<tr>
<td>@Html.TextBoxFor(m => m.Bar)</td>
</tr>
This works fine, except that the default model binder generates names like [0].Bar
. However, [
and ]
are invalid characters for the jQuery validate plugin and thus I am always receiving the following error whenever it tries to validate my input:
Syntax error, unrecognized expression: label[for='[0].Bar'], label[for='[0].Bar'] *, #[0].Bar
Is there any way to get the plugin to work while keeping my view bound to the model?
Update: I am using jQuery Validate and Microsoft's Unobstrusive Validation library (yep, the default ASP.NET MVC setup), so I am not directly writing any validation code at all, just if it's of interest!
The [ and ] characters aren't strictly invalid for jQuery validate plugin. It's just a sloppy coding which doesn't account for possibility to have those chars in name/id.
There is even a GitHub issue Handling ASP.NET MVC Input Arrays Exception for this.
What I did is I took the code from issue (it has a small problem on it's own) and added this hack on my JavaScript initialization code:
That might not be pretiest or best solution but it works for me. At least till it's fixed in jQuery.
No need to use this, as it's working with 1.13.1 (see issue above for discussion). Be warned, though I haven't checked myself, but ASP.NET MVC still could come bundled with 1.13.0