views:

32

answers:

2

Hi everyone,

Can anyone show me how to use jquery in an asp.net nested masterpage. I have my main masterpage where I have added the link to the jquery libaray and also the validation framework. I have then created another masterpage with some styling and created a aspx page based on that masterpage.

How can I attach the validation framework to textboxes within my page?

I have tried

         $("#aspnetForm").validate({
            rules: {
                <%=txtPostCode.UniqueID %>: {
                    minlength: 2,
                    required: true
                },
                 <%=txtContactEmail.UniqueID %>: {                        
                    required: true,
                    email:true
                }
            }, messages: {
                <%=txtPostCode.UniqueID %>:{ 
                    required: "* Required Field *", 
                    minlength: "* Please enter atleast 2 characters *" 
                }
           }
        });

However nothing happens. Can anyone point me in the right direction?

A: 

Because ASP.NET mangles the ID's, your best bet may be to just set CSS classes for your server controls and access them that way:

<asp:textbox id="Text1" cssclass="myText" runat="server" />

$('.myText').whatever();

It's not the most efficient JS because you're selecting by classes instead of IDs, but it will save you headaches down the road from trying to deal with ASP.NET mangled IDs in WebForms.

Jason
+1  A: 

You can write wrapper methods that pass IDs to jQuery functions, and call those methods either with RegisterStartupScript or inline JS on the child pages:

Javascript:

function makejQueryOnMangledNamesLessPainful(firstSelector, secondSelector)
{
    $(firstSelector).whatever();
}

.aspx:

<script>
   makejQueryOnMangledNamesLessPainful('#<%=Thing.ClientID%>',
                                       '<%=OtherThing.GetClientSelector()%>);
</script>

where GetClientSelector returns a string that's a selector, either just an ID or potentially some server-derived set of classes. Or anything else, really.

DDaviesBrackett