OnClientLoad Property in Asp.Net - javascript

In .aspx page when we are using radcombobox and all, onclientload attribute has been used.....
To handle that OnclientLoad Handler function has been written in javascript.
Actually what my ques is what is the use of OnclientLoad Property and OnClientLoad Handler Function in that. When it has to used. what are all the arguments it can accept... How it is working...
This is the program i have tried
<script type="text/javascript" language="javascript">
var rad_CatType_Id, radcb_OfferFormat, Rad_Footer;
function OfferFormat_onClientLoadHandler(sender, args) {
radcb_OfferFormat = sender;
}
</script>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<table class="table_Style">
<tr>
<td style="width: 15%">
Select Grade Category
</td>
<td style="width: 20%">
<Telerik:RadComboBox AutoPostBack="true" runat="server" ID="radcb_GradeCat" Width="165px"
MarkFirstMatch="true" CausesValidation="false" OnClientLoad="rad_Cattype_onClientLoadHandler">
</Telerik:RadComboBox>
</td>
<td>
<asp:CompareValidator ID="cmp_cat" runat="server" ErrorMessage="Please select Category"
ValidationGroup="List" ControlToValidate="radcb_GradeCat" ValueToCompare="Select"
Operator="NotEqual"></asp:CompareValidator>
</td>
</tr>.....
Anyone please help me with detailed example..
Thanks in Advance.......

The OnClientLoad client-side event occurs after the combobox | RadControl has been fully initialized on the client-side.
The event handler receives one parameter:
The combobox instance firing the event.
This event is helpful if you need to get the client-side instance of the combobox when it is embedded in other controls. Hook the OnClientLoad event and get the client-side instance of the combobox as demonstrated in the example below. This technique can be used to retrieve the combo instance for use elsewhere.
function OnClientLoadHandler(sender) {
var combo;
combo=sender;
}
<telerik:RadComboBox
ID="RadComboBox1"
runat="server"
OnClientLoad="OnClientLoadHandler" .../>
This technique may not work when AJAX is used. The asynchronous
requests may interfere with the OnClientLoad event.

Related

Trigger c# Event from JavaScript Function

I'm trying to call c# event from javascript function. I tried this:
<script type="text/javascript">
function LikeClick() {
document.getElementById('<%=Helper.ClientID %>').click();
}
</script>
<asp:Button ID="Helper" runat="server" OnClick="Helper_Click" />
But it doesn't trigger the c# event.
I believe a <asp:Button> will natively post the form back without a client side event handler. You need a control that does not natively post back but instead uses a client side click handler to call the __doPostBack() function.
Change
<asp:Button ID="Helper" runat="server" OnClick="Helper_Click" />
to this
<asp:LinkButton ID="Helper" runat="server" OnClick="Helper_Click" />

Javascript-error on finding object

im stuck with Javascript in Asp.net...
I made a TextBox named tbValidFrom and another named tbValidTo.
I also made two ModalPopups.
Then i try to open the ModalPopupExtenders when the TextBoxes get focus:
<script type="text/javascript">
$('#tbValidTo').focus(function () {
$find('ModalPopupExtenderNV1').show();
})
$('#tbValidFrom').focus(function () {
$find('ModalPopupExtenderNV2').show();
})
</script>
but it doesnt finds tbValidTo or ModalPopUpExtender ?
Runtime-Error in Microsoft JScript: Object expected
Here is one of the two ModalPopupExtenders and TextBoxes:
<asp:TextBox ID="tbValidFrom" runat="server"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanelNV2" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<cc1:ModalPopupExtender ID="ModalPopupExtenderNV2" runat="server" TargetControlID="HiddenField6"
PopupControlID="PanelNewVersion" BackgroundCssClass="modalBackground" BehaviorID="ModalPopupExtenderNV2"
Enabled="True" />
<asp:HiddenField ID="HiddenField6" runat="server" />
</ContentTemplate
</asp:UpdatePanel>
The same as above is with the other ModalPopupExtender and TextBox...
Help would be really nice.
Thanks
Edit: Yes i use a masterpage!
Fails where it is marked yellow.
your jQuery syntax is wrong.
change your script to:
<script type="text/javascript">
$('#tbValidTo').focus(function () {
$(this).find('#<%=ModalPopupExtenderNV1.ClientID%>').show();
});
$('#tbValidFrom').focus(function () {
$(this).find('#<%=ModalPopupExtenderNV2.ClientID%>').show();
})
</script>
elements that has runat="server" will eventually end with a different ID than you entered in the aspx file.
i used the <%= %> to get the 'final' id.
hope that helps
Seeing that markup there is two chances for the issues.
With the ModalPopupExtender.
Where you have given the panel "PanelNewVersion" . Seems like its missing in the markup.
In the Javascript code. If you want to hide that Popup, give the name of the panel. NOt the name of the ModalPopupextender.
Also you have given an update panel there in page, so you can easily handle the modalpopup in any srever side event of your textbox.
Otherwise, if you want to use the Modal popup ijn client side, use jQuery Modalpopup. That will the better option.
ASP.NET Can modify the ID's of elements, if you use a Masterpage the element id's will be modified to something like the following : ctl001_ContentPlaceHolder1_tbValidFrom
To get around this ASP.NET modification of your elements you can use ASP.NET Inline Expressions to get the rendered ID from the object.
See the answer to the following question for more information on ASP.NET Inline Expressions
You can look at changing the Client ID Mode (The way ASP.NET Modifies IDs when the page is rendered) here :
ASP.NET Client ID Modes
EDIT :
The AjaxControlToolkit's ModalPopupExtender is not rendered on the page as a html element, therefore you cannot find this item using the ClientID of the ModalPopupExtender.
You must use the BehaviourID to call the show function on.
The below code should work correctly :
$('#<%= tbValidTo.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV1').show();
})
$('#<%= tbValidFrom.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV2').show();
});
This will find the textbox object using the ASP.NET Inline expressions to find the client ID and will then find the behaviour ID and execute the Show method.
Example Markup :
<script type="text/javascript">
$(document).ready(function() {
$('#<%= tbValidFrom.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV2').show();
});
});
</script>
<asp:TextBox ID="tbValidFrom" runat="server"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanelNV2" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<cc1:modalpopupextender id="ModalPopupExtenderNV2" runat="server" targetcontrolid="HiddenField6"
popupcontrolid="PanelNewVersion" backgroundcssclass="modalBackground" behaviorid="ModalPopupExtenderNV2"
enabled="True" />
<asp:HiddenField ID="HiddenField6" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="PanelNewVersion" runat="server">
testing panel
</asp:Panel>

asp:Button in jQuery dialog box not firing OnClick event

I have an asp:Button inside a jQuery dialog for which the OnClick event isn't firing. I'm using the PostBackUrl property to navigate to another page, but I want to set this property in the OnClick event so that I can append a query string variable according to the name of a file they upload in the dialog. I posted a question about this dialog earlier, because I couldn't get it to post back at all, but that's been fixed. Clicking the button posts back fine, and I can set the PostBackUrl property in the asp markup, or in the Page_Load() of the code behind. But I can't get the OnClick function to fire for some reason, and that's where I want to set the PostBackUrl. Here's the .aspx...
<form id="frmDialog" runat="server">
<asp:Button ID="btnDisplayDialog" runat="server" Text="Click to Display Login Dialog" OnClientClick="showDialog(); return false;" />
<div class="divInnerForm"></div>
<div class="divDialog" style="display: none">
<table style="width: 100%;">
<tr>
<td>First Name: <asp:TextBox ID="txtFirstName" runat="server" Text=""></asp:TextBox></td>
<td>Last Name: <asp:TextBox ID="txtLastName" runat="server" Text=""></asp:TextBox></td>
</tr>
<tr>
<td>
How Old are You?
<asp:DropDownList ID="ddlAge" runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:DropDownList>
</td>
<td>
How Many Siblings do You Have?
<asp:DropDownList ID="ddlNumberSiblings" runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
What is your birthday?
<input type="text" id="datepicker" name="datepicker" />
</td>
</tr>
<tr>
<td>
Please Choose a Picture to Upload:
<asp:FileUpload ID="fupUserPicture" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnUserPicture_Click" />
</td>
</tr>
</table>
</div>
</form>
...the jQuery script that displays the dialog and places it within the form...
function showDialog() {
$('.divDialog').dialog({
modal: true, show: 'slide', width: 500,
open: function (event, ui) {
$('.divInnerForm').append($(this).parent());
}
});
}
...and the code behind with my OnClick function....
protected void btnUserPicture_Click(object sender, EventArgs e)
{
string fileName = "";
if (fupUserPicture.HasFile)
{
try
{
fileName = Path.GetFileName(fupUserPicture.FileName);
fupUserPicture.SaveAs(Server.MapPath("~/Images/" + fileName));
}
catch (Exception ex)
{
}
btnSubmit.PostBackUrl = "~/Profile.aspx?pic=" + fileName;
}
}
EDIT: Ok, here's how the submit button in the dialog actually renders as HTML. I think this may be the problem. As you can see, the javascript onclick simply provides "Profile.aspx" as the post back url, even though it seems to me any server side code should execute first and foremost. This is within the form...
<input id="btnSubmit" type="submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnSubmit", "", false, "", "Profile.aspx", false, false))" value="Submit" name="btnSubmit">
..and here's how it renderes if I remove btnSubmit.PostBackUrl = "~/Profile.aspx" from the Page_Load() function....
<input id="btnSubmit" type="submit" value="Submit" name="btnSubmit">
EDIT 2: ok so I've added another hidden asp button outside of the dialog, and the button inside the dialog now calls a javascript function which triggers the OnClick event of the hidden button. Same thing, the javascript function runs fine, but btnHidden_Click() function does not run! I'm at a total loss, at this point I literally have no idea why this isn't working. Here's the new Hidden Button, outside of the dialog div but inside of the form as you can see....
</div>
<asp:Button ID="btnHidden" runat="server" Text="" Visible="false" ClientIDMode="Predictable" OnClick="btnHidden_Click"/>
</form>
...here's the button inside the dialog with the OnClientClick event, which as I've said runs fine...
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="forcebtnHiddenClick(); return false;" />
And here's the OnClick function in the code behind for btnHidden, though it's exactly the same as before...
protected void btnHidden_Click(object sender, EventArgs e)
{
string fileName = "";
if (fupUserPicture.HasFile)
{
try
{
fileName = Path.GetFileName(fupUserPicture.FileName);
fupUserPicture.SaveAs(Server.MapPath("~/Images/" + fileName));
}
catch (Exception ex)
{
}
Response.Redirect("~/Profile.aspx?pic=" + fileName);
}
}
...and the javascript function that runs, but for some reason doesn't result in btnHidden_Click running...
function forcebtnHiddenClick(e) {
//__doPostBack('btnHidden', 'OnClick');
$('#btnHidden').trigger('click');
}
..as you can see I've tried both .trigger('click') and __doPostBack(), both to no avail.
EDIT: Ok, so the problem is definitely the
function forcebtnHiddenClick() {
__doPostBack('btnHidden', '');
}
function, which is not actually triggering the btnHidden_Click event. When I make btnHidden visible and click it directly, the btnHidden_Click function runs fine.
EDIT: After TONS of searching, found this and got it to work...
function forcebtnHiddenClick() {
<%= ClientScript.GetPostBackEventReference(btnHidden, string.Empty) %>;
}
I don't know why
__doPostBack(<%= btnHidden.ClientID %>, '')
doesn't work.
Try this
function showDialog() {
$('.divDialog').dialog({
modal: true, show: 'slide', width: 500
});
$(".divDialog").parent().appendTo($("form:first"));
}
You should be appending divDialog to the form not that empty divInnerForm.Then your button will be in the form and its on click event will fire happily.
Update
Try also using onclient click.Then wire this attribute to a function which will force a post back on the hidden button.
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="forceClick();" />
<asp Button id="hidButton" runat="server" onclick="hidButton_Click" />
function forceClick(){
__doPostBack('<%#hidButton.UniqueId %>');
}
Then use the event handler hidButton_Click to put your code.
$(this).parent().appendTo('form')
should work fine.. Append it to the form to fire server side events
When I use the jQuery dialog, I always use the buttons that come as part of the dialog. Then when they're clicked, I call a javascript function to perform my action.
If I need to handle a PostBack from those buttons, then I create a separate ASP.Net button on the page - this is the button I use to handle my OnClick event. The user won't click this ASP.Net button, though (I hide it with css so it's not visible on the page). Instead, the javascript function I call when they click the dialog button will call code that will mimic a click of my ASP.Net button.
The result is that when the dialog button is clicked, the page will PostBack as though the ASP.Net button was clicked, and I can handle it via my OnClick event.
Here's some sample code (in VB.Net)...
Dim csm As ClientScriptManager = Page.ClientScript
Dim js As New StringBuilder
js.AppendLine("function handleSubmitMyButton() {")
js.AppendLine(csm.GetPostBackEventReference(MyButton, ""))
js.AppendLine("}")
csm.RegisterClientScriptBlock(Me.Page.GetType, "create_call_to_MyButton", js.ToString, True)
When the page is built, it will include the handleSubmitMyButton() javascript function. The dialog button click will call this function, which will trigger the PostBack as though the 'MyButton' button was clicked.
Usually I don't have to hide the ASP.Net button with css. It's often the button that gets clicked to open the dialog. I prevent the PostBack when it opens the dialog; then when the dialog button is clicked, I mimic the click of that button.
UPDATE:
I saw several people mention the following line of code
$(this).parent().appendTo(jQuery("form:first"));
I thought that's what you were attempting to do with your line of code:
$('.divInnerForm').append($(this).parent());
If that doesn't do the same thing, though, you would need to have the code to add your fields to the form.
I use the modal dialog and i need to add a row, otherwise i get the modal transparency over the close button!
var $ObjDialog = $("div[id*='div_MyPopup']");
$ObjDialog.dialog({
modal: true
});
$ObjDialog.parent().prev().appendTo($("form:first"));
$ObjDialog.parent().appendTo($("form:first"));

setting label value in javascript

I have code like this
<table>
<tr>
<td>
<div>
<asp:Label runat="server" ID="lblBookmarksIds" Style="visibility: hidden;" Text="test"/>
</div>
</td>
<td>
<asp:UpdatePanel runat="server" ID="buttonPanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button runat="server" ID="btnInvokeImageRead" CausesValidation="false" UseSubmitBehavior="false"
OnClick="btnInvokeImageRead_Click" Style="visibility: hidden;" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
in javascript i'm trying to set value of label and call codebehind function so that i will have desired value passed to codebehind like that :
alert(document.getElementById('<%= lblBookmarksIds.ClientID%>').firstChild.nodeValue);
document.getElementById('<%= lblBookmarksIds.ClientID%>').innerText = str;
alert(document.getElementById('<%= lblBookmarksIds.ClientID%>').firstChild.nodeValue);
//alert('1');
if (str != "") {
document.getElementById('<%= btnInvokeImageRead.ClientID%>').click();
}
when second alert gets displayed the value of lblBookmarksIds has changed value, but when i debug in codebehind function btnInvokeImageRead_Click the value of lblBookmarksIds has its old value.
Anybody knows Why ?
Regards
Wojciech
Labels are not passed to code behind. You will have to use an input(TextBox) for that purpose.
You can style an input to look like a label using CSS.
Alternatively, you can keep the value in a hidden field, and use javascript to show the value in a label and pass it back in the hidden field.
The reason ASP.NET is able to "see" the values entered into a TextBox and similar controls is because the values of these controls are sent in the POST body when the page posts back. You can see this through any number of tools, including the Developer Tools your browser likely includes or an intercepting proxy like Fiddler. When the postback occurs, each of those controls has a LoadPostData function that processes the POST data and updates the Text properties (or whatever properties) of the control.
The contents of a Label are not submitted in the POST data, so .NET has no way to see any changes made to it from JavaScript.
The controls that do process post data all implement IPostBackDataHandler.

How to determine usercontrol selected child

I have a user control, a dropdown list, that's comprised of many component controls.
The main HtmlInputText will post back on an enter but on loss of focus it doesn't and I need that to update other controls.
I added an onblur function, and it gets called, but I only want to postback when the element getting focus isn't part of the user control.
How do I determine what is selected and if it's a child of the control?
Markup:
<%# Register Assembly="MultiDropDown" Namespace="MultiDropDownLib" TagPrefix="MultiDropDownLib" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table style="width: 328px">
<tr>
<td>
ProductClass
</td>
<td>
<MultiDropDownLib:MultiDropDown ID="MultiDropDown1" runat="server" TextBoxClass="textboxDD"
PostOnBlur="true" />
</td>
...
And in the control:
if (PostOnBlur)
{
txtItemList.Attributes.Add("onblur", string.Format("PostBack();", this.ClientID));
}
In the PostBack I want to determine what has focus and if it's part of the control. The original control came from: http://www.codeproject.com/Articles/219977/MultiDropDown-A-multiple-selection-Dropdown-contro
This is a way to do it with javascript and jQuery:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$(":input").focus(function () {
if (this.name.indexOf("$WebUserControl1") > -1) {
alert("It is child of my control.");
}
});
});
</script>
Just replace $WebUserControl1 with the name of your user control. This could also be Dynamic if you want to. Basically all of the children of the usercontrol will contain the name of their parent because WebUserControls inherit from TemplateControl which implements the INamingContainer interface.
Good luck.

Categories