views:

465

answers:

2

I've created an editor templace in an mvc app, and I want to restrict the input of each text box in the template to only numbers.

At render time, the template my be rendered multiple times on the page because the view could have multiple properties that are of type phone number, so the actual IDs of the text boxes will get unique names. What is the best way for me to add some jquery code to the template, reducing duplication of code, and being able to handle the issue of the ID's being dynamically generated by the mvc framework?

Below is my template:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PhoneNumber>" %>
<span>
(<%= Html.TextBox("AreaCode", (Model == null) ? "" : Model.AreaCode, new { size = 3, maxlength = 3, style = "width:25px" })%>)&nbsp;
<%= Html.TextBox("Prefix", (Model == null) ? "" : Model.Prefix, new { size = 3, maxlength = 3, style = "width:25px" })%>-
<%= Html.TextBox("Suffix", (Model == null) ? "" : Model.Suffix, new { size = 3, maxlength = 4, style = "width:35px" })%>&nbsp;
<%= Html.TextBox("Extension", (Model == null) ? "" : Model.Extension, new { size = 10, maxlength = 10, style = "width:55px" })%>
</span>
A: 

You should create a user control as your "template" and use a binding prefix according to some id uniquely identifying the user control.

Like:

Html.TextBox("Contact1.AreaCode", [...])

But I think you'll have to fetch back the values yourself.

Or you can create your own model binder to handle your list.

Mike

Mike Gleason jr Couturier
+2  A: 

Set each textbox to have a specific css class. Then use jquery to work on the class rather than id. You can also then remove some of the html attributes and define it specifically in your css class.

<%= Html.TextBox("AreaCode", (Model == null) ? "" : Model.AreaCode, 
    new { size = 3, maxlength = 3, @class = "number-textbox" }) %>

//jquery
$('.number-textbox').each(function()
{
   //validate numbers method
});

//css
.number-textbox
{
    width: 25px;
}
David Liddle
Good idea, thanks.
Jeremy