My code :
<%# Page Language="C#" %>
<script runat="server">
void button_Click(object sender, EventArgs e)
{
label.Text = "Refreshed by server side event handler at " + DateTime.Now + ".<br>Value provided:" + text.Text;
}
</script>
<html>
<head>
<title>How to update an UpdatePanel with JavaScript</title>
<script type="text/javascript">
function UpdPanelUpdate(id) {
var obj = document.getElementById("<%= text.ClientID %>");
obj.value = id;
__doPostBack("<%= button.ClientID %>", "");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
Update the Panel
<asp:TextBox ID="text" runat="server" Style="display: none;"></asp:TextBox>
<asp:Button ID="button" runat="server" OnClick="button_Click" Style="display: none;" />
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional" ChildrenAsTriggers="false">
<contenttemplate>
<asp:Label ID="label" runat="server"></asp:Label>
</contenttemplate>
<triggers>
<asp:AsyncPostBackTrigger ControlID="button" EventName="Click" />
</triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
That works great, but when I use it with a Masterpage, the link does´t seems to work... No error, but nothing happens...
Any idea?
Thanks!
In your JavaScript try using UniqueID instead of ClientID:
function UpdPanelUpdate(id) {
var obj = document.getElementById("<%= text.UniqueID%>");
obj.value = id;
__doPostBack("<%= button.UniqueID%>", "");
}
Let me know if that works.
I suspect what's happening is the textbox ID is no longer what you expect it to be. The ID is originally "text" however once you move that page to a Master Page things change. Since controls are now contained in the master page their IDs effectively change to show this relationship. So instead of the textbox's ID being "text" it is now going to be something like ctl00$cphBody$text - where "ctl100" is the Master Page's ID prefix and "cphBody" is the value you assigned to that page's ContentPlaceHolderID, respectively.
Sure, from the code behind you can do this.text.Text = "new value" and directly access it. That's fine. But try using FindControl and you'll notice things get confusing. The easiest way to really understand what I am describing is to do the following on your page with it using the master page:
Set a breakpoint on page load
Bring up your Immediate Window (CTRL + ALT + I)
Type this in: ?this.text.ID (you should see text)
Type in: ?this.text.ClientID (you should see ctl00_cphBody_text)
Type in: ?this.text.UniqueID (you should see ctl00$cphBody$text)
Now test the results you got for steps 3-5 using FindControl. Use ?this.FindControl("text") and ?this.FindControl("ctl00_cphBody_text") and ?this.FindControl("ctl00$cphBody$text") - all but the last one should return null.
To further understand this I suggest reading this article, specifically the section titled "FindControl, JavaScript, and Naming Containers."
EDIT: I'm actually unable to test the function at the moment, but I'm wondering if what I posted about FindControl applies to JavaScript accessing the control. Based on this article it seems ClientID is suggested over UniqueID. So this may not work.
Have you ensured the ScriptManager is included correctly on the master page? You might find this link useful; Using the ASP.NET UpdatePanel Control with Master Pages
Related
I have an update panel on a page which contains nested Panels. It has a Panel with a small form (like a log-in form) and a button. When the button is clicked, a few conditions are checked, and if passed, the first Panel is hidden and the second Panel with a larger form is displayed.
Because the larger form can take some time to load (it pulls data from other sources), the small form panel contains an UpdateProgress control.
All of this works fine.
Then I added a nested Panel within the login form Panel, placed under the UpdateProgress that will display a meaningful error message, such as if the login code is incorrect. This displays as expected. However, if the user then corrects their information and clicks the button again, the UpdateProgress displays properly, but the error message remains visible, even though I try to set it to Visible = false in code-behind.
This page does not use a master page.
Debugging shows that the Visible property does get set to false, although it still displays in the browser.
ASPX code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="custom_Default" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<!-- meta and link tags -->
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<!-- h1 and all that -->
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlLogin" runat="server">
<!-- label and text field -->
<asp:Button ID="btnBegin" runat="server" OnClick="btnBegin_Click" />
<asp:UpdateProgress ID="updProgress" runat="server" AssociatedUpdatePanelID="pnlUpdate">
<ProgressTemplate>
<p>Loading, please wait... </p>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:Panel ID="pnlMessage" runat="server" Visible="false">
<asp:Literal ID="ltlMessage" runat="server" />
</asp:Panel>
</asp:Panel>
<asp:Panel ID="pnlMainForm" runat="server" Visible="false">
</asp:Panel>
<asp:Panel ID="pnlConfirmation" runat="server" Visible="false">
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
<!-- javascript - jquery and bootstrap -->
</body>
</html>
Code Behind (I've tried setting visible to false in the Page_Load, in the pnlUpdate_Load event, and in the btnBegin_Click event - but that error message will not go away.
protected void btnBegin_Click(object sender, EventArgs e)
{
pnlMessage.Visible = false;
Page.Validate();
if (Page.IsValid)
{
// check some conditions. if fails:
ltlMessage.Text = "Reason for failure";
pnlMessage.Visible = true; // works
}
}
I have tried removing the Visible="false" from the pnlMessage on the ASPX page and placing it in the code behind in Page_Load but I still can't hide it after the message has already been displayed.
How can I hide the pnlMessage Panel after the btnBegin is clicked the second time?
I managed to find the solution to this. Apparently there isn't a way to do it in .NET - it has to be done in JavaScript.
Here is the code I used to accomplish this.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(initializeRequest);
prm.add_endRequest(endRequest);
var _postBackElement;
function initializeRequest(sender, e) {
if (prm.get_isInAsyncPostBack()) {
e.set_cancel(true);
}
$get('pnlMessage').style.display = 'none';
}
function endRequest(sender, e) {
$get('pnlMessage').style.display = 'block';
}
</script>
I've got an issue with a messagebox user control. I wish for a control which can be given a message and the user can dismiss with a click of a button, which can be inserted into many places.
I have applied the javascript into the messagebox control in a hope i can keep everything to do with the messagebox centralized, however when browsing to a page with the messagebox control added i get this error:
CS1061: 'ASP.components_messagebox_ascx' does not contain a definition for 'HideBox' and no extension method 'HideBox' accepting a first argument of type 'ASP.components_messagebox_ascx' could be found
The control is as thus:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Messagebox.ascx.cs" Inherits="FosterNetwork.Components.Messagebox" %>
<script type="text/Javascript">
function HideBox() {
document.getElementById("PNL_Messagebox").setAttribute("visible", false);
}
</script>
<asp:Panel ID="PNL_Messagebox" runat="server">
<asp:Label ID="LBL_Message" runat="server" />
<asp:Button ID="BTN_Ok" Text="Ok" OnClick="HideBox()" runat="server" /> <!--Error happens on this line-->
</asp:Panel>
I'm fairly certain i've done this right but obviously i've done something wrong if it's not working. Any light on the situation at all would be grand.
Addendum: If i comment out the Button control the page loads fine, and the script loads fine too (Viewed page source)
The control ID's you're referencing are not the client ID's, but server ID's. So retrieve the 'ClientID' from the control in the JavaScript function and second, use the 'OnClientClick' property to show the JavaScript message.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Messagebox.ascx.cs" Inherits="FosterNetwork.Components.Messagebox" %>
<script type="text/Javascript">
function HideBox() {
document.getElementById("<%= PNL_Messagebox.ClientID %>").setAttribute("visible", false);
}
</script>
<asp:Panel ID="PNL_Messagebox" runat="server">
<asp:Label ID="LBL_Message" runat="server" />
<asp:Button ID="BTN_Ok" Text="Ok" OnClientClick="HideBox()" runat="server" /> <!--Error happens on this line-->
</asp:Panel>
Onclick looks for a server side function, and not javascript. either, define your button as <input type='button' onclick='HideBox' or change the current code to:
<script type="text/Javascript">
function HideBox() {
document.getElementById("<%= PNL_Messagebox.ClientID %>").setAttribute("visible", false);
return false;
}
</script>
<asp:Button ID="BTN_Ok" Text="Ok" OnClientClick="return HideBox()" runat="server" />
returning false in OnClientClick, prevents the asp button from postback.
Edit: as Monty mentioned, your panel control's client id is not correctly set in your code.
I have a simple JQuery enabled ASP.NET page:
<script>
$(document).ready(function() {
$("#accordion").accordion();
});
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="accordion">
<h3><a id="Accordion1" href="#">Accordion Panel 1</a></h3>
<div>
A form input...
<asp:Button id="btnSubmit" runat="server" onclick="btnSubmit_Click" />
</div>
<h3><a id="Accordion2" href="#">Accordion Panel 2</a></h3>
<div>
Some content...
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
If you'll notice, I'm using an UpdatePanel also.
btnSubmit_Click event does something like this:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Some MySql INSERT, etc.
}
Now what I want to do is for server-side btnSubmit_Click to trigger JQuery to "click" Accordion Panel 2 (so it will open Accordion Panel 2 and close 1). How to do this?
UPDATE: Sorry guys I forgot to mention earlier that It's got an UpdatePanel
Oh well, I just used the "change the value of a hiddenfield after postback then let jquery read that hiddenfield" approach. Thanks guys!
Jquery:
var tag = $("#contentBody_hfTag1").val();
if (tag=="1") { $(".Accordion").accordion({ active: 1 }); }
else { $(".Accordion").accordion({ active: 0 }); }
.aspx
<asp:HiddenField ID="hfTag1" ClientIDMode="Predictable" Value="0" runat="server" />
C#
protected void btnMyButton_Click(object sender, EventArgs e)
{
hfTag1.Value = "1";
}
You can't. Jquery runs on the client, your handler is on the server. You will need to trigger the event on the client when the page reloads after the post back.
You can't do that as Jquery works on client side, from a server side event, as the page reloads. And the state of the accordion will be lost. So what you can do is, instead of making a post back, you can do the same work in a Jquery AJAX call on the button click to do whatever you want and then close the accordion 1 and show accordion 2.
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<i88:InlineScript runat="server">
<script type="text/javascript">
$('Accordion2').click()
</script>
</i88:InlineScript>
<asp:Button ID="cmd" runat="server" Text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
You can put inlineScript which will get Executed every time you update the Panel.
You can also use jQuery.Trigger(); for other event's.
I know this must sound really basic but I'm really stumped here. What I'm trying to do is to show a Hyperlink once a process has completed. And this process is the AsyncFileUpload. In the ASPX page, I want to create an but have it hidden on the initial page load. If I set the Style="display: none;" seems to work but after the file upload, nothing I do, will make the control visible again. When the file is uploaded, it calls a function called FileUploadComplete. It's in here that no matter what I do, the Hyperlink won't display.
Any help is greatly appreciated :)
Thank you,
dave
Here is the ASPX Code (with recently added javascript)
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="OptionsPlaceHolder" runat="server">
<script language="javascript" type="text/javascript">
function ShowLink() {
$("#openFile").show();
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolderBody" runat="server">
<asp:UpdatePanel ID="updImportFile" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="pageHeader">
<asp:Literal runat="server" ID="pageTitle" Text="<%$ Resources:Resources, ImportFile %>" />
</div>
<ajaxToolkit:AsyncFileUpload ID="FileUpload1" runat="server" Width="600px"
UploaderStyle="Traditional" OnUploadedComplete="FileUploadComplete" ThrobberID="throbber"
CompleteBackColor="#E9F2FD" OnClientUploadComplete="ShowLink" />
<asp:Image runat="server" ID="throbber" ImageUrl="images/loading.gif" />
<br />
<asp:Hyperlink runat="server" ID="openFile" NavigateUrl="~/OpenFile.aspx" Text="Open"
style="display:none;"/>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
And here is the code behind:
protected void FileUploadComplete(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string importName = Server.MapPath(#"Uploads\") + FileUpload1.FileName;
FileUpload1.SaveAs(importName);
// Import the JSA
JSA jsa = new JSA();
jsa.Import(importName);
// Show the Hyperlink
ShowLink();
}
}
private void ShowLink()
{
openFile.Attributes["Style"] = string.Empty;
}
I didn't include the master page code. It has the ToolkitScriptManager in it.
Are you trying to show on client-side or server-side? Is the link a client-side, or server-side object? Javascript would be the standard way.
If the control is a client-side object:
document.getElementById("hyperlink_name").style.display = "block";
Or if it is a server-side object:
document.getElementById("<%= hyperlink_name.ClientID %>").style.display = "block";
I would recommend getting jQuery and using the following though:
$('#hyperlink_name').show();
Or you can use an ASP.Net Link Button and do it server-side:
linkButton.Visible = true;
It would be more helpful if you would post some of the code you have tried already so that we can get a better idea of where you are.
{first answer deleted}
[EDIT :I didn't catch that you are using AsyncFileUpload when I first read the question]
Using AsyncFileUpload inside an update panel the server is being accessed via a partial postback, as a result other controls (the hyperlink) cannot be affected on the server. This will require that you make use of javascript (or preferably jquery) to make the change on the client.
You can do it on OnClientUploadComplete function, but you have to reference the hyperlink like this: <%= hyperLink.ClientID %>.style.display = 'block';
Another more asp.net way is to use update panels. Put the hyperlink into an UpdatePanel and set a trigger on the UpdatePanel when the file is uploaded. then change the visibility on the server at UploadedComplete event.
I have a master page that contains an image as follow:
<asp:Image ID="imgCompanyLogo" runat="server" ImageUrl="image path" />
and in a child page I want to edit the property ImageUrl as follow:
Image imgCompanyLogo = (Image)Page.Master.FindControl("imgCompanyLogo");
imgCompanyLogo.ImageUrl = ResolveUrl("~/images/CompanyLogo/Logo.png");
and it doesn't give me an exception, but it doesn't change anything.
Note: I have an UpdatePanel in the child page.
Since the image is sitting outside of the UpdatePanel, server side changes will not be executed on the image after a partial postback. Your only option is to inject JavaScript into the page and change the image URL.
Use the ScriptManager.RegisterStartupScript Method to inject JavaScript after the partial postback.
Something like the following will work for you:
C#
protected void btnPostback_Click(object sender, EventArgs e)
{
imgCompanyLogo.ImageUrl = ResolveUrl("~/images/CompanyLogo/Logo.png");
ScriptManager.RegisterStartupScript(btnPostback,this.GetType(), "myScript", "ChangeImage('" + ImageUrl + "');",false);
}
JavaScript
function ChangeImage(imgURL) {
//make sure the ID of the image is set correctly
document.getElementById('imgCompanyLogo').src = imgURL;
}
Wrap image by UpdatePanel with UpdateMode="Always"
Master Page:
<asp:UpdatePanel runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Image runat="server" ID="Image1" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
public void SetImageUrl(string url)
{
Image1.ImageUrl = url;
}
Child Page:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button Text="Click Me" runat="server" OnClick="UpdateImage" />
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateImage(object sender, EventArgs e)
{
((Main)Master).SetImageUrl("~/Images/0306d95.jpg");
}
The code above works well for me.
Have a look at Sys.WebForms.PageRequestManager Class. Define handler in javascript and may change the image source.
If your code is being run after an async postback (per your UpdatePanel) then changes to anything outside the UpdatePanel will not be rendered. Content in the master page would definitely seem to qualify.
If this is what you're trying to do, this model won't really work. You will need to use some client script to effect changes to already-rendered content when working with this model.
An UpdatePanel is a construct to identify an area that's updated through ajax. The page is not actually reloaded. So an postback can never change content that's outside of the UpdatePanel (or control bound to that panel) that sourced it.
Here's a basic implementation (using jQuery). Add a hidden field to pass the new source to the client. This must be inside the UpdatePanel. Change this value from the server when you want the image to update with new_image_src.Value=ResolveUrl(...);
<asp:HiddenField ClientIdMode="Static" runat="server" id="new_image_src"
value="" EnableViewState="false">
Give your image a static id too to make life easier:
<asp:Image ClientIdMode="Static" runat="server" id="dynamic_image" ImageUrl="..." >
Add javascript to the page (should NOT be in the UpdatePanel):
function updateImage() {
var new_src=$('#new_image_src');
if (new_src) {
$('#dynamic_image').attr('src',new_src);
/// erase it - so it won't try to update on subsequent refreshes
new_src.val('');
}
}
$(document).ready(function() {
/// adds an event handler after page is refreshed from asp.net
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(updateImage);
});
This wouldn't be difficult to do without jquery either but seems more common than not these days.