I have a linkbutton inside an updatepanel:
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="upSaveComplete" ClientIDMode="Static">
<ContentTemplate>
<asp:Panel ID="Panel90" runat="server" CssClass="navInnerDiv" Width="200px" ClientIDMode="Static">
<asp:Panel ID="Panel91" runat="server" CssClass="navInnerDivContents">
<asp:Panel ID="Panel92" runat="server" CssClass="navInnerDivContentsTop">
<asp:Panel ID="Panel93" runat="server" CssClass="navInnerDivContentsTopSubTwo">
<asp:ImageButton ID="ibSave" ImageUrl="~/theImages/Save.png" runat="server" CssClass="navImages" OnClick="btnSave_Click" />
<br />
<asp:LinkButton ID="btnSave" runat="server" Text="Save" ClientIDMode="Static" OnClick="btnSave_Click" CssClass="linkOff" />
</asp:Panel>
</asp:Panel>
<asp:Panel ID="Panel94" runat="server" CssClass="navInnerDivContentsBottom">
Task Actions
</asp:Panel>
</asp:Panel>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
code behind:
protected void btnSave_Click(object sender, EventArgs e)
{
ShowMessage();
if (CheckSameUser() == strUser)
{
UpdatePanel upTDNotes = (UpdatePanel)ContentMain.FindControl("upTaskDetailRight");
if (upTDNotes != null)
{
upTDNotes.Update();
}
//MessageBox.Show(lblTDNotes.Value);
string strSaveQuery = #"{QUERY}";
//MessageBox.Show(strSaveQuery);
using (SqlConnection scConn = new SqlConnection(strMainConn))
{
try
{
scConn.Open();
SqlCommand cmd = new SqlCommand(strSaveQuery, scConn);
cmd.ExecuteNonQuery();
Session["queryChanged"] = "Yes";
}
catch (Exception ce)
{
}
}
}
else
{
}
Response.Redirect("YourTasks.aspx");
}
public void ShowMessage()
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
When I click the Save button, the alert isn't being displayed. I have ScriptManager already on the page but it still didn't work.
How can I modify my code so I am able to see the alert (or even a confirm) window on click on the link/image
Cut down to its most basic level, your code says this:
ShowMessage();
if (CheckSameUser() == strUser)
{
// Stuff
}
else
{
}
Response.Redirect("YourTasks.aspx");
So you set up the bit of javascript to be run ... and then you send an instruction down to the browser to redirect to the page "YourTasks.aspx".
The javascript was set up to render when your page was sent down to the browser ... but you are redirecting before your page can be rendered, so that javascript never reaches the browser, and therefore never executes.
If what you want is to have the message display on the client immediately on click, and then have the server go and do something (like save your data and then send you to a new page), your best bet would be to hook the javascript up to a client-side event, like the submission of the form. You can do this easily with jQuery or even with basic javascript (although the update panel can complicate things a bit.)
Related
I'm in need of a synchronous call from code-behind ASP.NET (C#) to a Javascript function.
I've tried the ScriptManager.Registerclient, but as this is asynchronous this is no good. I'm in need of some testing in javascript before returning a value (updating an UpdatePanel) to check whether or not the operation is valid.
For a short code example:
myButton_click(object sender, EventArgs args)
{
<callJavascriptSynchronous>
if (MyHiddenField.Value == "true")
//Do
else
//Don't
}
MyHiddenField is within an UpdatePanel. For the javascript function:
function javascriptFoo(myInteger)
{
var returnValue = window.external.TestInteger(myInteger);
document.getElementById('<%=MyHiddenField.ClientID%>').value = returnValue;
}
The UpdatePanel looks like this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:HiddenField ID="MyHiddenField" runat="server" ClientIDMode="Static" Value="" Visible="false"/>
</ContentTemplate>
Any suggestions on the synchronous call?
Thanks!
Edit: Added full code:
MyPage.aspx:
function javascriptFoo(myInteger)
{
var returnValue = window.external.TestInteger(myInteger);
document.getElementById('<%=MyHiddenField.ClientID%>').value = returnValue;
}
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:HiddenField ID="MyHiddenField" runat="server" ClientIDMode="Static" Value="" Visible="false"/>
</ContentTemplate>
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
MyPage.aspx.cs:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
ScriptManager.RegisterStartupScript(UpdatePanelContext, UpdatePanelContext.GetType(), "AlertTest", "AlertTest()", true);
string sVal = HiddenFieldContext.Value;
if (sVal == "true") //do
else //don't
}
When you're in your button's click-event, you've already left the frontend and cannot jump back for a function call. Execute the function first, clientside, upon the button-click (read about the OnClientClick event), then return your result with the postback.
This link addresses the same issue.
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! :)
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;
I've got a ValidationSummary and SuccessLabel in the MasterPage
When the SuccessLabel has detail in it, and then the ValidationSummary then fails validation I want it to hide the SuccessLabel and only show the ValidationSummary.
<div id="ApplicationStatus" class="ValidationSummaryContainer">
<asp:Label ID="StatusLabel" CssClass="SuccessSummary" runat="server"
Visible="false"></asp:Label>
<asp:Label ID="WarningLabel" CssClass="WarningSummary" runat="server"
Visible="false"></asp:Label>
<asp:ValidationSummary ID="ErrorValidationSummary" runat="server"
CssClass="ValidationSummary" DisplayMode="List" />
<asp:CustomValidator ID="ErrorCustomValidator" runat="server"></asp:CustomValidator>
</div>
<div id="ApplicationContent" class="ApplicationContentContainer">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StatusLabel.Text = "Successfully loaded record";
}
}
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:Textbox ID = "Text1" runat="server"/>
<asp:RequiredFieldValidator id="InputTextBoxRequiredFieldValidator" runat="server"
ControlToValidate="Text1" Visible="false" CssClass="InlineNoWrap" Enabled="true">
</asp:RequiredFieldValidator>
<asp:Button ID = "Button1" runat="server" Text="Submit"/>
</asp:Content>
I'm trying to find a way in JavaScript to catch the validation error and hide the StatusLabel.
I don't want to have to put a javascript function on every button on every page that uses the MasterPage.
Thanks,
Alex
How about something like this:
protected void Submit(object sender, EventArgs e)
{
if (IsValid)
{
StatusLabel.Visible = true;
}
else
{
StatusLabel.Visible = false;
}
}
Your validation code are totally miss lot of fields.
ok now we are going your pint .
Set visible false in your label for page load event
then success time add the label text ,and set visible true
you miss control to validate and validationgroup and display fields
please see this sample
I'm trying to get my hovermenuextenders to do some lazy loading. I have avatars across the site that when hovered over should pull back various things (images, recent posts, post count, etc) For obvious reasons I don't want to do this for all avatars on the page_load.
Using the following code I'm able to get the hover event to trigger a postback to the server asynchronously (breakpoint is hit onmouseover). However, the commands in the postback don't seem to be reflected after execution is done. The loading image/label stay in the hover panel. Any help is appreciated!
EDIT: I just realized that the very last avatar rendered on the page works properly but none of the ones above it do. Any ideas what might be causing this strange behavior?
<script language="javascript" type="text/javascript">
function OnHover(image) {
__doPostBack('<%= this.imageHoverTrigger.UniqueID %>', '');
}
</script>
<!-- DUMMY Hover Trigger -->
<input id="imageHoverTrigger" runat="server" style="display:none;"
type="button" onserverclick="imageHoverTrigger_Click" />
<!-- User Avatar -->
<div style="border: solid 1px #AAA; padding:2px; background-color:#fff;">
<asp:ImageButton ID="UserImg" runat="server" />
</div>
<!-- Hover tooltip disabled by default
(Explicitly enabled if needed)-->
<ajax:HoverMenuExtender ID="UserInfoHoverMenu" Enabled="false" runat="server"
OffsetX="-1"
OffsetY="3"
TargetControlID="UserImg"
PopupControlID="UserInfoPanel" dyn
HoverCssClass="userInfoHover"
PopupPosition="Bottom">
</ajax:HoverMenuExtender>
<!-- User Profile Info -->
<asp:Panel ID="UserInfoHover" runat="server" CssClass="userInfoPopupMenu">
<asp:UpdatePanel ID="UserInfoUpdatePanel" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Image ID="loadingImg" runat="server" ImageUrl="~/Design/images/ajax-loader-transp.gif" />
<asp:Label ID="loadingLbl" runat="server" Text="LOADING..." ></asp:Label>
<asp:Panel ID="UserInfo" runat="server" Visible="false">
<b><asp:Label ID="UserNameLbl" runat="server"></asp:Label><br /></b>
<span style="font-size:.8em">
<asp:Label ID="UserCityLbl" runat="server" Visible="false"></asp:Label> <asp:Label ID="UserStateLbl" runat="server" Visible="false"></asp:Label>
</span>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="imageHoverTrigger" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
And the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
UserImg.Attributes.Add("onmouseover", "javascript:OnHover(this)");
}
protected void imageHoverTrigger_Click(object sender, EventArgs args)
{
// Hide loading image/label
loadingLbl.Visible = false;
loadingImg.Visible = false;
//TODO: Set user data here
UserInfo.Visible = true;
}
Figured it out:
My Page_Load event hookup should've been:
UserImg.Attributes.Add("onmouseover", "javascript:OnHover('" + this.imageHoverTrigger.UniqueID + "','" + this.hiddenLbl.ClientID + "')");
UserImg.Attributes.Add("onmouseout", "javascript:ClearTimer()");
and the javascript function should've been:
var hoverTimer;
// Called on the hover of the user image
function OnHover(trigger, hiddenTxt) {
var field = document.getElementById(hiddenTxt);
// Only post if this hover hasn't been done before
if (field == null || field.innerHTML == "false") {
hoverTimer = setTimeout(function() { ShowInfo(trigger) }, 500);
}
}
// Clears timeout onmouseout
function ClearTimer() {
clearTimeout(hoverTimer);
}
// Retrieves user info from server
function ShowInfo(trigger) {
__doPostBack(trigger, '');
}
I also added a hidden field on the form in order to know when the hover has been executed. The code behind sets the hidden field to true and my javascript checks for the value of the hidden field each time it executes. This stops the code from doing round trips each time the user hovers over the image.