problem with masterpage and jquery - c#

I have a MasterPage that inside its content section I added a FORM element.
When accessing that page, all my controls are renamed since the FORM is runat=server.
And thus when selecting in jquery, even the form has been renamed
How can I fix that?
thanks

With a master page, all elements will have ct100__etc appended to the ID of the element. This is a feature since its a naming container. Typically, the way to work around it is to use syntax like:
$("#<%= button.ClientID %>").click(..);
To access the longer ID's, or rely on CSS classes to identify elements. Another trick is to wrap certain sections of the form with a DIV HTML element and give it an ID to target.
HTH.

You can't, that's the behavior of .Net. What you can do is adjust your jquery usage to incorporate the ClientID of the controls you're using. The easiest way is to have some sort of translation variable injected into script in the head somewhere.
<script language="javascript">
var myControl1 = '<%=myControl1.ClientID %>';
</script>
Then you can use myControl1 as a string variable to inject the client id into your jquery calls in a more readable fashion.

Have a look at this post here
http://john-sheehan.com/blog/custom-jquery-selector-for-aspnet-webforms/
Explains it all pretty clearly. the trick is to use ClientId

In addition to the .ClientID approach suggested in many of the other answers, you can use jQuery's endswith selector.
eg: Select the element whose id endswith "myid" (eg ctl001_form1_myid)
$('[id$="myid"]');
or if you are using .net 4, you can set ClientIdMode="false" to prevent the renaming.

You can use Control.ClientID for this. Something like
$("#<%= yourelement.ClientID %>")

You can also create a CSSCLASS and then access by $('.classname')
<asp:TextBox id="tb4" Text="Hello World!" cssclass="txtboxtb4" runat="server" />
alert($('.txtboxtb4').val());

Another way is put controls in span tag.
<span id="txt">
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
</span>
Than you can select you element like this in jQuery.
$('#txt > input').val('Hello world');
But my way is, select element with ends with selector.
$('input[id$="txt"]').val('Hello world');
Works for my cases. Hope help.

Related

How can I get the Server Side ID of a UserControl?

I need to do a __doPostBack in a WebForms of this LinkButton:
<asp:LinkButton ID="AggiungiSocial" runat="server" onclick="cmdAggregaSocial_Click">Link</asp:LinkButton>
I see that .NET process it as:
javascript:__doPostBack('ctl00$ContentPlaceHolder1$Dashboard1$RepeaterSocials$ctl00$AggiungiSocial','')
so what I need is javascript:__doPostBack('ctl00$ContentPlaceHolder1$Dashboard1$RepeaterSocials$ctl00$AggiungiSocial','').
But rendered, the ID is instead ContentPlaceHolder1_Dashboard1_RepeaterSocials_AggiungiSocial_0
So Do I need to do a javascript replace/parse of that ID or is there a method to get this "__dopostback" UserControl id?
Such as:
var ServerIDUserControl = link.attr('href').replace("javascript:__doPostBack(", "").replace("','')", "");
(which is terrible imo).
(Perhaps depending on which (ASP).NET version you're using) the name attribute value will contain the string you're looking for, as opposed to the id being made identifier-friendly. An example from a 3.5 site here at work looks like this for a Button:
<input type="submit"
name="ctl00$cph_main$ctl00$PerformSearch"
id="ctl00_cph_main_ctl00_PerformSearch">
I parenthesise the first part simply because I have to admit my ignorance as to when/why this happened - I recall a time when this wasn't the case, and it could be either a 3.5+ thing or a configured thing.
Otherwise you could use the inline server-side script syntax to output the control.UniqueID in the appropriate place.
To get the id of the control sent as __EVENTTARGET during postback you need to use the UniqueID property of Control. In your case:
javascript:__doPostBack('<%= AggiungiSocial.UniqueID %>', '');
However, from your example I see that your control is nested inside a repeater called RepeaterSocials. In this case, your code might look like this:
javascript:__doPostBack('<%= RepeaterSocials.Items[0].FindControl("AggiungiSocial").UniqueID %>', '');
But my advice is to not use this approach. You can instead capture the Repeater.ItemCommand event and see which button was clicked inside the repeater.

Is it considered bad practice if you use an <input> for a textbox compared to <asp:Textbox>?

I have an ASP.NET page that contains a form and a button. In order to use the OnKeyPress and a javascript function (to stop the user from using the enter key and without adding a FilteredTextBoxExtender) attribute I had to change the <asp:Textbox> to an <input> with type="text".
Is this considered bad practice? Or are there valid situtations where should be used?
To ensure this question isn't subjective - are there any other ways to prevent the user using the enter key when typing in an ASP.NET textbox? (without putting code in the code behind)
In General you should use Asp.Net control only when is strictly required ad the classic HTML are much faster as they don't need any server elaboration to be rendered
If you want your input to be accessed by .NET code-behind then it's considered best practice to use the TextBox control. You can put a runat=server on an input, but only when you must.
If it were me, I'd use the , add an ID and set the ClientIDMode="Static" if possible, or add a class with CssClass="class", then use jQuery to handle the onKeyPress even with something like this:
$('.class').on('change', function() {
});
You do not need to change the control type in order to use client side events in javascript.
The control has a ClientId property that can be used for binding the event to (using getElementById, for example).
You can add JavaScript to <asp:TextBox />. You can either attach the JavaScript using the ClientID of the control, or you can add it in the codebehind using
MyTextBox.Attributes.Add("onKeyPress", "myJavaScriptFunction()");
You should just use the ClientID of your asp:TextBox
here is an example using jQuery :
<asp:TextBox ID="inputTB" runat="server"></asp:TextBox>
<script language="javascript" type="text/javascript">
$('#<%=inputTB.ClientID%>').keypress(function (e) {
if (e.which == 13) // return key
{
return false;
}
});
</script>

Change the id of the body tag from code-behind

I'm curious:
Is it possible to change the the id of the body tag from code-behind (in ASP.Net Webforms)?
I want to change
<body id="test">
to
<body id="foo">
without having to use a second MasterPage. (Our designer provided two different html/css files where the id of the body tag is different. Except for that small difference, I could use the same MasterPage)
Do I really need to create another MasterPage, just for the different body tag?
You can have a bodyId variable in the MasterPage:
<body id='<%= bodyId %>'>
And then you can set the variable from the content page.
ID of page elements is same as name of variables, can you change them? if yes you can do this also, if no, it's possible!
You can do it on client side too.
See here : http://jsfiddle.net/fTvpQ/2/

Use jQuery for find text box in ASP.NET page

I have <asp:TextBox runat="server" ID="lastName" /> on a page and I want to set focus it with jQuery but it is not returning it. My code is like this:
$.ready() {
var tb = $('lastName').focus(); // don't work, why?
}
You have two different problems here that you need to resolve: a malformed selector and the fact that in ASP.NET client IDs don't match server IDs.
What you want is:
$.ready() {
$('#<%= lastName.ClientID %>').focus();
}
Let's break it down...
First, in jQuery a selector that accesses an element by it's id attribute needs to begin with a '#' symbol. So the accessor should look more like: $('#lastName'). Selectors in jQuery are similar, but more robust than in CSS. You can familiarize yourself with the selector syntax at the jQuery API site.
Second, with ASP.NET, the id's assigned to the HTML elements are often different than those that identify an asp control on the server. This is because ASP.NET needs to make sure that all elements are uniquely identified - and don't collide with names that may be defined in master pages, user controls, or repeated sections of content. These ids tend to get long and are often impossible to predict - fortunately, we can use the <%= %> code expansion together with the ClientID property of the control to insert the appropriate id for the HTML element without having to know the details of how ASP.NET assigns unique ids.
In ASP.NET 4.0, the client ID can now be specified directly, which can help avoid the technique shown above.
Here is a function I use for selecting server controls in pages that have a masterpage. It doesnt work in all cases such as nested controls but for simpler stuff its real handy.
This goes on the masterpage somewhere
<script type="text/javascript">
baseName = "<%= Content.ClientID %>_";
</script>
Using this function you can go GetServerElementById("lastname")
function GetServerElementById(id) {
return $("#" + baseName + id);
}
You can do a partial attribute query:
<script type="text/javascript">
$(function() {
$('#btnExtract').click(
function() {
alert($("input[id$='txtMessage").val());
}
);
});
Selecting ASP.NET Web Controls in jQuery

How to set value of <input type="hidden"> in asp .net page_load without using runat="server"

i need to do the following two things...
i want to set value of in asp .net page_load. the problem is that i dont want to use runat="server". i have tried this the following but it does not work:
HtmlInputHidden hiddenControl = (HtmlInputHidden) FindControl("a");
is there a way to access in asp .net page_load without using runat="server"? ? ?
i can do this if i use but in this case i cannot access it in master page's javascript function. i have tried this but it does not work...
var hdnField = document.getElementById('<%= hdnIdentity.ClientId%>');
var hdnField = document.getElementById("hdnIdentity").getAttribute("value");
var hdnField = document.getElementById("hdnIdentity").value
what i need... i want to access content page's hidden field value in javascript in master page. is there a way ? ? ? thnx in advance regards Haroon haroon426#yahoo.com
I sometimes do the following, especially when I want control over my ids (especially when using jquery).
<asp:literal id="literal1" runat="server"><input type="hidden" id="someid" value="{0}"/></asp:literal>
Then, in codebehind you can set the value with the following:
literal1.Text = string.Format(literal1.Text, "somevalue");
This doesn't really get around using runat="server", but you haven't specified why you don't want to do that. Also, you'd have to get the value with a request.form
Update
In .net 4.0 you have much more control over your IDs. See this for more information:
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
IIRC, you need to look in the HttpRequest.Forms, somewhere in there.
If the value is part of a POST form then you want to check Request.Forms or Request.QueryString if it's a GET form.
ad 1) in aspx file just write <input type="hidden" value="<%=GetHiddenValue%>" />. And in your code behind define protected property
public class MyPage : Page {
protected GetHiddenValue { get { /*...*/ } }
You can use it in your master page javascript how ever the control name is not what you expect it to be you'd need to use ClientID to get that. If you do not apply runat=server you can only get a hold of the control as text by either traversing the .aspx file or as some one mentioned embedding it in a named tag and then doing string manipulation on the inner HTML. That is for setting it. If you need to get the value use Request[tagName] or similar
ad 2) You can use simple html code in your content page with specified id <input type="hidden" id="myHiddenField" />. Then in master page javascript use document.getElementById('myHiddenField').

Categories

Resources