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.
Related
I have a div tag that has a click event and the method I'm trying to call is from the codebehind.
This is my div tag
<div class="DivA" runat="server" id="ThisDiv" onclick="<%ClickMe();%>"></div>
The method is a simple
public void ClickMe()
{
Response.Redirect("www.google.ca");
}
I'm just testing this before I add the real stuff to it. The error that it is throwing is...
JavaScript critical error at line 16, column 49 in http://localhost:24307/DIVPAGE.aspx
SCRIPT1002: Syntax error
this is the line that it is giving me
<div id="ThisDiv" class="DivA" onclick="<%ClickMe();%>"></div>
I have tried changing the
<%ClickMe();%>
to
<%=ClickMe()%>
But that throws the same error. Another thing I don't understand is when you look at the line with the error that it is missing the runat tag and has added other characters to the onclick event.
Thanks
You have a concept problem here, do this, and test it will work:
<asp:LinkButton id="lbClickMe" runat="server" OnClick="ClickMe">
<div class="DivA" id="ThisDiv">
The Click Me Button!
</div>
</asp:LinkButton>
That's it, when runat=server is specified ASP.NET page parser will process the element as server side, so for this elements/controls no server tags in markup are allowed except data binding tags inside control templates. So to call you method you have to put a runat server on a control that haves the Click event, this is the case of the LinkButton, inside of him you can put your div for some specific styling of your UI.
Also not that, if you really want to have the your div behaving like that, there is no problem in complicating what is simple, but in that case please do this instead:
<asp:LinkButton id="lbClickMe" runat="server" OnClick="ClickMe" Visible="False"></asp:LinkButton>
<div class="DivA" id="ThisDiv" onclick="<%= Page.GetPostBackEventReference(lbClickMe) %>"></div>
The GetPostBackEventReference extracts the javascript code necessary to simulate your link button click, but once more is preferable to use directly the link button if you can.
Hope it helps,
Regards.
The <%= %> syntax emits a string, it doesn't do anything, like a redirect.
You need to do your redirect client-side with this javascript:
window.location = 'http://my.url.com';
If you need to interact with server side code, you need to do so with AJAX communicating to a web service to get the URL you need, and then performing the redirect described above.
Update
Sorry lads, brain freeze.
Yes, indeed, you can inject a string that will be evaluated as a click handler, but the handler must be a javascript function, not a server-side one! Once the page is rendered, it can no longer interact with the server save for communicating with a web service (or if we want to get technical, web sockets as well).
You can't call server-side C# methods from the DOM like that. You can only call JavaScript functions in an HTMLElement's onclick handler.
It is correct that you can call server-side methods using the template language, however this will be executed at the time of rendering the page; you could, for example, render the results of that server-side method, but you can't use a server-side method as a handler for a client-side event. The onclick event on a DOM element can only call a JavaScript function.
ASP web controls also have an OnClick event attribute, which is probably what's confusing you; this is different from the onclick event attribute on DOM elements (ASP will create additional code for its web controls, e.g. in case of an asp:button). This works using ViewState and a postback to the server. The onclick event for a DOM element however won't do those things for you.
Adding runat="server" will convert your element to an ASP control, however it will only be an HtmlControl. In the case of a <div>, it will be an HtmlGenericControl which simply writes out the onclick attribute of your element as it is.
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>
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.
Is there a way to call a javascript function when the selectedIndex of a select input has been changed?
Using this code in the c# code behind file
riskSeverityDropDown.SelectedValue = Convert.ToString(planRisk.Severity);
riskSeverityDropDown.SelectedIndexChanged += new EventHandler(riskSeverityDropDown_SelectedIndexChanged);
riskSeverityDropDown.AutoPostBack = true;
want to change something else on the page with javascript when the index is changed.
Any help would be much appreciated.
Thanks in advance
You're already going to server code (AutoPostBack is true), which means you're going to rebuild the entire page anyway. Running javascript at this point would be a little silly, because any changes you make to the DOM will be lost and any ajax requests you want to send can instead be handled by normal server code. If you really want to do this, you can just register the script to run when the page loads after the postback.
On the other hand, if you can do this without any server code at all then set AutoPostBack to false and the basic html select control has a nice onchange event you can handle.
Simply add an onchange to your asp:dropdownlist.
<asp:DropDownList ID="riskSeverityDropdown"
AutoPostBack="True"
SelectedIndexChanged="riskSeverityDropDown_SelectedIndexChanged"
onChange="functionName()"
runat="server" />
or to do this from codebehind use:
riskSeverityDropdown.Attributes["onchange"] = "functionName()";
You want to add an attribute to that drop down called "onchange" and set it to call a JavaScript method of your choosing.
Use JQuery. It exposes a rich set of events that you can use to code against practically anything in a uniform manner. It is also quite easy to learn, compact, and popular.
In short you can't go wrong if you use JQuery. It is meant to solve problems like this well.
I am trying to change a label's text by using server-side JavaScript (onclick) and C# within the page_load event. For example, I would like to write something like the following:
Label1.Attributes.Add("onclick", "Label2.text='new caption'")
Does anyone know the correct code for this? Also, what is this type of code referred to; is it just JavaScript or JavaScript in C# or is there a specific name? Lastly, does a book or online resource exist that lists the choices of control.attributes.add("event", "syntax") code to use with C#?
There is no server-side Javascript (unless you change to a platform other than ASP.NET where you actually use Javascript as server language). What you are doing is adding an attribute to the html tag, and the code will be executed entirely on the client side.
First, let's look at how it's done in HTML without the server side code and server side controls:
<span onclick="document.getElementById('Label2').innerHTML='Thank you';">Click me</span>
<span id="Label2"></span>
To use Label controls instead, setting the onclick attribute from server side code, you would do like this:
Label1.Attributes.Add("onclick", "document.getElementById('Label2').innerHTML='Thank you';");
This will work as long as the controls are not inside a naming container. If they are, the id of the controls are prepended with the name of the container to keep them unique, so you need to use the ClientID property to find out what their final id is:
Label1.Attributes.Add("onclick", "document.getElementById('" + Label2.ClientID + "').innerHTML='Thank you';");
The ClientID always contains the id that you can use to access the element from Javascript, so the last code always works regardless if the control is in a naming container or not.
To find out what attributes you can use, you should look at the HTML documentation, for example the Internet Explorer documentation for the span element. When looking at the documetation for a specific feature, notice the Standards Information, as that will tell you if it works in any browser or just in Internet Explorer.
The code above adds JavaScript to a server control rendered on the client. Take a look at this MSDN article - Using JavaScript Along with ASP.NET for more information.
IIRC, you will need to reference Label2 by its ClientID and will need to write some JavaScript to change the label's text value (I think ASP.NET labels get rendered as <span> tags).