Button in UpdatePanel triggers event, but the page doesn't update - c#

Here's the markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="well well-large">
<form class="navbar-form pull-left">
<asp:FileUpload ID="test" runat="server" CssClass="input-small" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" CssClass="btn" OnClick="btnUpload_Click" />
</form>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnUpload" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Panel runat="server" ID="panAlert" Visible="false">
<div class="alert alert-success" id="divAlert" runat="server">
<button id="Button1" runat="server" type="button" class="close" data-dismiss="alert">×</button>
You shouldn't see this message!
</div>
<asp:Panel runat="server" ID="panMarquee" Visible="true">
<div id="Div1" runat="server" class="progress progress-success progress-striped">
<div id="ProgressBar" runat="server" class="bar" style="width: 100%"></div>
</div>
</asp:Panel>
</asp:Panel>
When the btnUpload button is clicked, the server code is supposed to determine if the FileUpload control has a file. If it does, it will change the visibility of the Panel control to true. It works fine outside of the UpdatePanel.
Here's the server code:
protected void btnUpload_Click(object sender, EventArgs e)
{
this.SetMessage(Message.Success);
try
{
if (this.test.HasFile)
{
string filename = Path.GetFileName(GetUB04Doc.FileName);
//test.SaveAs(Server.MapPath("~/") + filename);
this.SetMessage(Message.Success);
}
}
catch (Exception ex)
{
//TODO: Do something with th exception
this.SetMessage(Message.Fail);
}
finally
{
//this.GetUB04Doc.Dispose();
}
}
private enum Message { Success, Fail }
private void SetMessage(Message msg)
{
if (msg == Message.Success)
{
this.divAlert.InnerText = "Well done! The document appears to have uploaded successfully. Please wait...";
this.divAlert.Attributes.Add("class", "alert alert-success");
}
else
{
this.divAlert.InnerText = "Oh snap! Something broke. Please contact IT right away.";
this.divAlert.Attributes.Add("class", "alert alert-error");
}
this.panAlert.Visible = true;
}
I tried putting the Panel in the ContentTemplate section as well, but the results were the same.
Any ideas on what I'm doing wrong here?

You should surround the area which you are modifying from an async postback in another UpdatePanel with UpdateMode is set to Conditional. Then update the other manually from codebehind:
<asp:UpdatePanel ID="panAlertUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="panAlert" Visible="false">
<!-- ....
codebehind:
// ...
this.panAlert.Visible = true;
panAlertUpdatePanel.Update()
Side-note: As #Belogix has already commented, you should use an AsyncFileUpload control in an UpdatePanel since a regular FileUpload control it's not supported with an asynchronous postback.
MSDN:
Controls that Are Not Compatible with UpdatePanel Controls:
...
FileUpload and HtmlInputFile controls when they are used to upload files as part of an asynchronous postback.
...
To use a FileUpload or HtmlInputFile control inside an UpdatePanel
control, set the postback control that submits the file to be a
PostBackTrigger control for the panel. The FileUpload and
HtmlInputFile control can be used only in postback scenarios.

you need to put PostBackTrigger instead of AsyncPostBackTrigger like this. <asp:PostBackTrigger ControlID="btnUpload" />

Related

Calling asp net button click event with JS will not call server side event

Sorry to post perhaps a silly problem here, but I'm at my wits end with it. I have a hidden field with a button inside an update panel like so:
<asp:UpdateProgress runat="server" ID="updprCompLines" AssociatedUpdatePanelID="updpanCompLines">
<ProgressTemplate>
<img src="../Images/ajax-loader.gif" alt="Please wait..." /> </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server" ID="updpanCompLines" UpdateMode="Conditional">
<%--<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnFillMembers" />
</Triggers>--%>
<ContentTemplate>
<div>
<asp:HiddenField ID="hdnField" runat="server" />
<asp:Button ID="btnFillMembers" runat="server" style="display:none;"
Text="DummyButton" onclick="btnFillMembers_Click" />
</div>
The update panel also contains a gridview and inside my gridview I have a link button:
<ItemTemplate>
<asp:LinkButton ID="lkbtBenefName" runat="server" Text='<%#Eval("COMPETENCE_CODE") %>'
OnClientClick='<%#Eval("COMPETENCE_LINE_ID", "return SelectedCompetence({0})") %>'/>
</ItemTemplate>
The call is to a JS function that is supposed to call the above button:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" EnablePageMethods="true"/>
<script type="text/javascript">
function SelectedCompetence(CompetenceLineId) {
document.getElementById('<%= hdnField.ClientID %>').value = CompetenceLineId;
var clickButton = document.getElementById('<%= btnFillMembers.ClientID %>');
clickButton.click();
}
</script>
Button click event method:
protected void btnFillMembers_Click(object sender, EventArgs e)
{
lblGvMemError.Text = "";
lblGvMemError.ForeColor = Color.Red;
if (hdnField.Value != null || hdnField.Value.ToString() != "")
{
try
{
int CompLineId = Convert.ToInt32(hdnField.Value);
GetSelectedCompLineMembers(CompLineId);
}
catch (Exception ex)
{
lblGvMemError.Text = "Error: " + ex.Message;
}
}
updpanCompLinesMembers.Update();
}
The problem is that while debugging, it never runs the click event and it doesn't give any error messages either. I don't understand, I have a similar form where this works; I don't get why it doesn't here... Any help please?
Have you confirmed that SelectedCompetence is being called via an alert or similar? Additionally, have you made sure that the clickButton variable is being assigned to successfully?
I know this isn't an answer, but don't yet have the reputation to comment, and sometimes it's the easy stuff so maybe this will help! :)

How to hide and display asp:buttons in asp.net from code behind?

I am working on asp.net web application.
In one Page I have two asp buttons.
I want to display them in one condition otherwise I don't want to display them.
So I'm trying to do the same like this. But Its not working.
I can't find the reason behind it. Please tell me where is the issue.
To Hide Buttons
if (!IsPostBack)
{
ButtonReplaceId.Style.Add("display", "none");
ButtonAssociateRules.Style.Add("display", "none");
}
To display buttons
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if(a==0)
{
ButtonAssociateRules.Style.Add("display", "block");
ButtonReplaceId.Style.Add("display", "block");
}
}
aspx for buttons
<div style ="padding-left:400px;">
<asp:Button ID="ButtonAssociateRules" runat="server" OnClick="AssociateMultipleRulesButtonClick"
CssClass="search_button_in_vm_intersection" Text="Associate Multiple Rules"
OnClientClick="return OnClientClickAssociateRewardRuleFile();" />
<asp:Button ID="ButtonReplaceId" runat="server" OnClick="ApplyReplaceIfRuleIntersects"
CssClass="search_button_in_vm_intersection" Text="Replace Previous Rules"
OnClientClick="return OnClientClickReplaceRewardRuleFile();" />
</div>
aspx of button for OnClick event ApplyAssociation()
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Table runat="server" CssClass="rule_file_whole" BorderWidth="0" Style="padding-top: 30px;">
<asp:TableRow ID="MerchantRowAssociation" HorizontalAlign="Center">
<asp:TableCell>
<div style="text-align: center">
<asp:Button ID="AssociationMerchant" Text="Apply Association" runat="server" OnClick="ApplyAssociation"
CssClass="search_button_in_vm_associate1 " OnClientClick="return checkValidation()" />
</div>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
Seeing as you are using a conditional update panel, you can try either of these after putting the buttons inside an update panel.
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if (a == 0)
{
ButtonAssociateRules.Style["visibility"] = "hidden";
ButtonReplaceId.Style["visibility"] = "hidden";
myUpdatePanel.Update();
}
}
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if (a == 0)
{
ButtonAssociateRules.Visible = false;
ButtonReplaceId.Visible = false;
myUpdatePanel.Update();
}
}
Here's an example of your buttons inside an update panel.
<asp:UpdatePanel ID="myUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div style="padding-left:400px;">
<asp:Button ID="ButtonAssociateRules" runat="server" OnClick="AssociateMultipleRulesButtonClick"
CssClass="search_button_in_vm_intersection" Text="Associate Multiple Rules"
OnClientClick="return OnClientClickAssociateRewardRuleFile();" />
<asp:Button ID="ButtonReplaceId" runat="server" OnClick="ApplyReplaceIfRuleIntersects"
CssClass="search_button_in_vm_intersection" Text="Replace Previous Rules"
OnClientClick="return OnClientClickReplaceRewardRuleFile();" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
You can simple use the Visible property of Button which is more straight forward and clean.
ButtonReplaceId.Visible = false;
If this property is false, the server control is not rendered. You
should take this into account when organizing the layout of your page.
If a container control is not rendered, any controls that it contains
will not be rendered even if you set the Visible property of an
individual control to true. In that case, the individual control
returns false for the Visible property even if you have explicitly set
it to true. (That is, if the Visible property of the parent control is
set to false, the child control inherits that setting and the setting
takes precedence over any local setting.) MSDN.
You are trying to change the state of control in ajax call that is not in current UpdatePanel. Put the buttons in the same UpdatePanel then you will be able to change the state.
ButtonReplaceId.Visible = false;
ButtonAssociateRules.Visible = false;

How can I prevent C# from redrawing a <div> I used jQuery to show

Scenario: I have a modal-style div that will be shown when the user clicks a button. At the time the div is shown, I need to get some data from the back-end to fill in some fields. Additionally, I'd like to use the jQuery method I use for all my modal windows (fades in the modal div, displays a background div as well as enabling the use of ESC key or "click offs" to close the modal).
It looks something like this:
<asp:ScriptManager ID="sc" runat="server" />
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<div class="window">
<h5>Test Form</h5>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</div>
</asp:Panel>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="backgroundPopup"></div>
So ... lnkShowIt calls both the jQuery (which will show pnlPopup) as well as the C# (which will populate tbxTime).
jQuery method actually just calls another method from a common js library I have that does the modal window stuff - I don't think that actual code is the problem but here is the simple function used for this page:
<script type="text/javascript" language="javascript">
function showForm() {
loadPopup('#pnlPopup');
}
</script>
Code behind methods look like this:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
}
}
I'm able to generate some level of success by doing the following but it seems like just a major hack and I have to assume there's a better approach:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
}
It seems like it should be easier than this, but the way the UpdatePanel keeps redrawing (and thus resetting the display:none on pnlPopup) is really causing me fits.
Thanks in advance
Solution I just found: putting the LinkButton in its own UpdatePanel and then the form in its own UpdatePanel and making sure the div that is the actual popup box is not in an UpdatePanel at all.
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:UpdatePanel ID="updLink" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<div class="window"style="min-width:500px;">
<h5>Here is a Test Form</h5>
<label>Time:</label>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:Label ID="lblText" AssociatedControlID="tbxText" runat="server" ViewStateMode="Disabled">Text:</asp:Label>
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Panel>
</div>
Seems to do the trick without any Script Registers from the codebehind

iFrame in UpdatePanel not updating

I'm trying to update the source of an iFrame when a button is clicked on the page. However, nothing seems to be happening...
.ASPX:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
<asp:Button ID="ValidateButton" runat="server" Text="Validate" OnClick="SubmitSponsor" />
</p>
</div>
<iframe runat="server" id="PayPalFrame" height="150px" width="100%" frameborder="0"></iframe>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void SubmitSponsor(object sender, EventArgs e)
{
var driver = new Driver();
var isvalid = driver.IsAppValid(URL.Text, APILINK, Connstring);
if (isvalid)
{
PayPalFrame.Attributes.Add("src", "http://www.google.com");
URLInvalid.Visible = false;
}
}
I've also tried:
PayPalFrame.Attributes["src"] = "http://www.google.com"; and still nothing.
I have tested your code, and it works in a sample project:
ASPX:
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
<asp:Button ID="ValidateButton" runat="server" Text="Validate" OnClick="SubmitSponsor" />
</p>
</div>
<iframe runat="server" id="PayPalFrame" height="150px" width="100%" frameborder="0">
</iframe>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Codebehind:
public partial class UpdatePanelIFrameTester : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitSponsor(object sender, EventArgs e)
{
bool isvalid = true;
if (isvalid)
{
PayPalFrame.Attributes.Add("src", "http://www.ironworks.com");
}
}
}
I would inspect your code and ensure nothing is causing your page to refresh/perform a full postback (I changed the URL as google will not allow you to view it in an iframe under standard conditions).
I believe you have to remove the src attribute and then re-add it, for this to work. Not sure why this is, but I remember doing it the last time I worked with update panels. Perhaps it's because the src attribute always already exists?
Anyway, here's some sample code: how to change the src attribute in iframe.

Scriptmanager on one page, but the Panel on another

Im having a .Master page with
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:ContentPlaceHolder ID="MasterIndhold_Member" runat="server">
</asp:ContentPlaceHolder>
And inside the ContentPlaceHolder I got an Panel with a FileUpload. The thing is that the FileUpload doesn't find the file. Here I want to add RegisterAsyncPostBackControl to the Scriptmanager, but how do I do this when the panel is on another page?
The nested page code looks like this
<asp:Content ID="Content3" ContentPlaceHolderID="MasterIndhold_Member" runat="server">
<asp:panel runat="server" ID="Panel_MyProfile_Member" Visible="false">
<asp:FileUpload ID="File1" runat="server" />
<asp:LinkButton ID="LinkUploadImageMember" runat="server" onclick="LinkUploadImageMember_Click">Upload</asp:LinkButton>
And the CodeBehind for the FileUpload Looks like this
protected void LinkUploadImageMember_Click(object sender, EventArgs e)
{
if (File1.HasFile == true)
{
if ((File1.PostedFile.FileName.EndsWith(".jpg")) || (File1.PostedFile.FileName.EndsWith(".jpeg")) || (File1.PostedFile.FileName.EndsWith(".png")))
{
byte[] input = File1.FileBytes;
Bruger.UploadImage(input, int.Parse(Request.QueryString["ID"]));
}
}
}
Please keep code examples to C# and ASP.NET as I'm new to this stuff ^^
Thanks
You could also use the ScriptManagerProxy class if you need a ScriptManager on your content page, but I'm not sure whether you need this at all. Do you really need an UpdatePanel on every content page? (because you declared it on the master page). I think it might be better to declare the UpdatePanel within the content page.
Try to define a trigger for your linkbutton, otherwise HasFiles is always false
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="LinkUploadImageMember" />
</Triggers>
<ContentTemplate>
<asp:FileUpload ID="File1" runat="server" />
<asp:LinkButton ID="LinkUploadImageMember" runat="server" Text=" upload " />
</ContentTemplate>
</asp:UpdatePanel>
If you cannot remove the UpdatePanel from the Masterpage, you could expose a property on the masterpage that gives access the updatepanel, like this:
public UpdatePanel MyUpdatePanel
{
get { return UpdatePanel1; }
}
From the contentpage you can access the update panel and update the triggers programmatically:
protected void Page_Load(object sender, EventArgs e)
{
((Site)Master).MyUpdatePanel.Triggers.Add(new PostBackTrigger() {
ControlID = LinkUploadImageMember.UniqueID });
}

Categories