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>

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.