hi I have one parent page which opens a pop up window, and user makes some changes on child pop up page then clicks a save button.
When the user clicks the save button, I want to doPostBack to the parent page so that the changes made in the pop up window can be seen in parent window.
Question : How can I achive the above scenario?
I want to write the script code in aspx.cs file, I tried
string script = "";
script = "<script>window.opener.__doPostBack('UpdatePanel1', '')</script>";
ScriptManager.RegisterClientScriptBlock(Literal1, typeof(Literal), "yenile", script, true);
but this did not do anything, no errors just nothing.
I am new to JavaScript, need help with all steps.
The parent page:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<div>
<asp:Literal runat="server" ID="ChildWindowResult" />
</div>
<hr />
<input type="button" value="Open Dialog" onclick="window.open('MyDialog.aspx', 'Dialog');" />
<asp:Button ID="HiddenButtonForChildPostback" runat="server"
OnClick="OnChildPostbackOccured" style="display: none;" />
<asp:HiddenField runat="server" ID="PopupWindowResult"/>
</ContentTemplate>
</asp:UpdatePanel>
The MyDialog page:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
function postData() {
var resultField = $("input[type='hidden'][id$='PopupWindowResult']", window.opener.document);
var parentPosDataButton = $("[id$='HiddenButtonForChildPostback']", window.opener.document);
resultField.val($("#<%= SomeValueHiddenField.ClientID %>").val());
parentPosDataButton.click();
}
</script>
<asp:TextBox runat="server" ID="SomeValueHiddenField" />
<asp:Button runat="server" OnClick="PostData" Text="Click Me" />
protected void PostData(object sender, EventArgs e)
{
SomeValueHiddenField.Value = DateTime.Now.ToString();
ClientScript.RegisterStartupScript(this.GetType(), "PostData", "postData();", true);
}
But I believe that it would be much better to utilize here some pop-up controls like PopUpExtender from the AjaxControlToolkit library or dialog from the jQuery-UI.
You probably need to use ClientID:
string script = "";
script = "<script>window.opener.__doPostBack('" + UpdatePanel1.ClientID + "', '')</script>";
ScriptManager.RegisterClientScriptBlock(Literal1, typeof(Literal), "yenile", script, true);
The last parameter is to whether include script tag or not
So, if you do
RegisterClientScriptBlock(page,type, "<script>foo();</script>", true);
You will end up with:
"<script><script>foo();</script></script>"
So, change your last parameter to false, or better yet, remove the tags in the string
Review the following suggested solution:
http://livshitz.wordpress.com/2011/06/12/use-popup-to-postbackupdate-its-parentopener-without-losing-viewstate-values-and-close/#more-16
Related
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 having an empty div and i am using LOAD method of jquery and getting data from another aspx page. it works fine. it gets File upload and button control from that page. now when i click on the button my button code doesn't get called and my dialog gets close.
jQuery On Page1.aspx
var checkP = $('#<%= productName.ClientID %>').val();
checkP = checkP.replace(/\ /g, '-');
$("#midDiv").load("UploadImages.aspx?prodName=" + checkP + " #midDiv");
$("#midDiv").dialog();
//It Shows Dialog With File Upload Option & Button Option.
Page1.aspx
<div id="midDiv">
</div>
Page2.aspx
<div id="midDiv">
<asp:FileUpload ID="productsImages" CssClass="hid" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="uploadImageTemp" Text="Button" />
</div>
Page2.aspx.cs //Code Behind
protected void uploadImageTemp(object sender, EventArgs e)
{
//Some Work Here...
}
Is there any way that my button code gets called or is there any way to keep jQuery modal open ?
Append your dialog in form like below.
var checkP = $('#<%= productName.ClientID %>').val();
checkP = checkP.replace(/\ /g, '-');
$("#midDiv").load("UploadImages.aspx?prodName=" + checkP + " #midDiv");
$("#midDiv").dialog().parent().appendTo($("form:first"));
Change your button control to link button control.
<div id="midDiv">
<asp:FileUpload ID="productsImages" CssClass="hid" runat="server" />
<asp:LinkButton ID="Button1" runat="server" OnClick="uploadImageTemp" Text="Button" />
</div>
Now call your code behind button click event.
Browse and Upload with using asp:FileUploadcontrol is working perfectly fine.
But It is two step process. First we have to browse and then select the file.
I want it working in single step So for making it single step I tried the following code:
protected void Button1_Click(object sender, EventArgs e)
{
//to launch the hidden fileupload dialog
ClientScript.RegisterStartupScript (GetType(),
"hwa", "document.getElementById('fileupload').click();", true);
//Getting the file name
if (this.fileupload.HasFile)
{
string filename = this.fileupload.FileName;
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('Selected File: '" + filename + ");", true);
}
else
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('No FILE has been selected');", true);
}
}
In this code, there is one fileUpload control that is being invoked on Button1_Click. Ideally it should execute the first line then A file Upload control should be shown and after selecting a file or canceling the dialog, flow should go to next line. But dialog is showing up after full function execution finishes.
Because of this asynchronous or not expected execution flow if (this.fileupload.HasFile) is returning false(because user has not been asked to select any file yet) and I am not getting the selected file name.
Can we modify this code to achieve file upload in single step? Or if any other way is possible to do this?
Note- I have asked not to use window forms and Threads. So solution by using these two is not acceptable.
You are missing the fact there is a client side/server side disconnect in the web environment.
Your line: ClientScript.RegisterStartupScript (GetType(),"hwa","document.getElementById('fileupload').click();", true); is client side code and will not be executed until the serverside script is comleted and the resulting HTML/javascript/CSS returned to the browser as it is client side javascript. YOu want to be leveraging the onchange event of the file upload control.
The question should help you out: ASP.NET FileUpload: how to automatically post back once a file is selected?
this is not exactly what you are looking for but it does what you want. difference is that instead of clicking a separate button you have to click the Browse button. and when you press the Open button, the page will postback. I have used JQuery for this. here's my code
ASPX
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="upload" style="display:none" />
</div>
<script type="text/javascript">
var isfirst = true;
$(function () {
$('#<%= fileupload1.ClientID %>').on('change', function (e) {
console.log('change triggered');
$('#<%= btn.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
});
});
</script>
</form>
</body>
Code behind
protected void btn_Click(object sender, EventArgs e)
{
//TODO
}
For the ones who land here late,
<div>
<asp:FileUpload ID="fu" runat="server" CssClass="bbbb" onchange="clickSeverControl()"/>
<asp:LinkButton Text="Upload" ID="lnkUpload" runat="server" OnClientClick="showUpload();return false;" OnClick="lnkUpload_Click"/>
</div>
hide the file control with css
<style>
.hiddenStyle {
visibility:hidden;
}
</style>
on client click event of link button trigger the click of file upload control
function showUpload() {
document.getElementById("fu").click();
}
on change event trigger the server side click
function clickSeverControl() {
__doPostBack('<%= lnkUpload.ClientID %>', 'OnClick');
}
on server click save the uploaded file
protected void lnkUpload_Click(object sender, EventArgs e)
{
fu.PostedFile.SaveAs(Server.MapPath("~/Upload") + "/" + fu.PostedFile.FileName);
}
Thanks for the other answer I have just combine two example and got the solution for my problem in my project
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnUploadBulk" runat="server" OnClick="btn_Click" Text="upload" style="display:none" />
</div>
<script type="text/javascript">
var isfirst = true;
$(function () {
$('#<%= btnUploadBulk.ClientID%>').on('click', function (e) {
showUpload();
})
});
function showUpload() {
var control = document.getElementById("<%= FileUploadControl.ClientID %>");
control.click();
}
</script>
</form>
Code Behind
protected void btn_Click(object sender, EventArgs e)
{
//TODO
}
This worked for me
im trying to update a variable from within an update panel:
<script type="text/javascript">
var v = 1;
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnDone" runat="server" Text="Done" onclick="btnDone_Click" />
<asp:Literal ID="litnew" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function updateint() {
alert(v);
}
</script>
<input type="button" onclick="updateint()" />
code behind
protected void btnDone_Click(object sender, EventArgs e)
{
string kiss = LipImageCreator.createImage(); //this returns a file path
litnewlipsurl.Text = "<script> v = '" + kiss + "'; </script>");
}
if i click the button run the updateint() function before i hit the btnDone button i get the alert saying '1' as expected. after i click the btnDone button the javascript is written to the literal as expected but when i click the updateint() button again i still get '1' and not the filepath i was expecting....
You must use ClientScript.RegisterStartupScript() to get the ajax handler to run your script when the postback completes.
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.