updating variable from within update panel - c#

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.

Related

How can I pass a value from a Button_Click event to Page_Load

It seems I am struggling with the order of the page life cycle. Based on the user selecting button 1 or 2, I need to have respective controls added dynamically during the Page_Load event. My problem is when a button is clicked the Page_Load event is executed before Button_Click event code is read. There for my variable "doWhat" is not assigned a value until after the Page_Load event. How can I have the "doWhat" variable assigned a value to be read during the Page_Load?
Below is asp.net form code for the two buttons:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
Below is the code behind:
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
doWhat = Convert.ToUInt16(ViewState["doWhat"]);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.ID == "Button1")
{
doWhat = 1;
}
else
{
doWhat = 2;
}
ViewState.Add("doWhat", doWhat);
}
If you are comfortable with javascript then you can achieve it by making following changes in your design and code. Add a hidden field in your aspx page. Your HTML code should be like this.
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button_Click" OnClientClick="return doWhatAction(1);" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button_Click" OnClientClick="return doWhatAction(2);" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:HiddenField ID="HiddenField1" Value="1" runat="server" />
<script type="text/javascript">
var doWhatAction = function (actionIndex) {
//alert(actionIndex);
document.getElementById("<%=HiddenField1.ClientID%>").value = actionIndex;
return true;
}
</script>
</div>
</form>
And your code will be something like...
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
//doWhat = Convert.ToUInt16(ViewState["doWhat"]);
doWhat = Convert.ToUInt16(HiddenField1.Value);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
//Do Nothing
//Button btn = sender as Button;
//if (btn.ID == "Button1")
//{
// doWhat = 1;
//}
//else
//{
// doWhat = 2;
//}
//ViewState.Add("doWhat", doWhat);
}
You can use jquery or javascript i this case.
Took on hidden variable in form
initialize it on click event of button in javascript
Read value of hidden variable in page load
<head >
<title>Hidden Variable</title>
<script type="text/javascript">
function SetHDNValue()
{
var hdnControlID = '<%= hdnControl.ClientID %>';
document.getElementById(hdnControlID).value=1;
}
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
<input id="hdnControl" type="hidden" runat="server" />
<asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="SetHDNValue()"
/>
</div>
</form>
</body>
And in code behind file hdnControl.value
Since long ago I am not working with asp.net forms. And forgot doing things.But I found how you can do. As on stackoverflow link like answers is wrong. I copied main statements from the link which indicate how post-back events works and how you can use it for your purpose. For more http://aspsnippets.com/Articles/How-to-find-the-control-that-caused-PostBack-in-ASP.Net.aspx
All controls accept Button and ImageButton use JavaScript for causing a postback. To enable postback on these controls one has to set AutoPostBack property to true.
When you set this property to true, __doPostBack function is called on event which causes a postback.
The __doPostBack function is not visible in Source of the page until you place a LinkButton or set AutoPostBack to true for any of the above discussed controls.
Here is how generated __doPostBack looks:
<script type = "text/javascript">
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
</script>
The __doPostBack function simply stores the below two arguments in two hidden fields
eventTarget – The name of the control that caused the postback
eventArgument – The argument to be sent to server.
In two hidden fields which also appear only when AutoPostBack is set to true
Finally, here is how you can distinguish by getting control's ID that caused the postback :
if (IsPostBack)
{
string CtrlID = string.Empty;
if (Request.Form["__EVENTTARGET"] != null &&
Request.Form["__EVENTTARGET"] != string.Empty)
{
CtrlID = Request.Form["__EVENTTARGET"];
/****implement Your logic depending on control ID****/
}
}

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! :)

ASP - file upload in single step

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

OnClick and OnClientClick

I have an image button on a pop up page which is opened by another page
<asp:ImageButton
ID="Button_kalem_islemikaydet"
runat="server"
CausesValidation="False"
ImageUrl="~/images/butonlar/buyuk/Kaydet.jpg"
meta:resourcekey="Button_kalem_islemikaydetResource1"
OnClick="Button_ust_islemikaydet_Click"
OnClientClick="f2()"
Width="100" />
f2() is
<script type="text/javascript">
function f2() {
opener.document.getElementById("TextBox1").value = "hello world";
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.location.href = window.opener.location.href;
}
</script>
And Button_ust_islemikaydet_Click is another method implemented in aspx.cs file and it updates the database tables which are shown in the parent page in a GridView.
What I am trying to do is to doPostBack I mean refresh the opener(parent) page.And with these above codes refresh is working.However, parent page still shows the same data before the refresh.And the reason is that OnClientClick works before OnClick method
So my question is that is there any way I can run the method on OnClick and finish it and then run the OnClientClick method?
<form id="aspnetForm" runat="server">
<asp:Button Text="Click Me" ID="ClickMeButton" OnClick="ClickMeButton_OnClick" runat="server" />
<asp:HiddenField runat="server" ID="UpdateOpenerHiddenField" Value="false" />
<script type="text/javascript">
//1st approach
var updateOpenerField = window.document.getElementById("<%= UpdateOpenerHiddenField.ClientID %>");
if (updateOpenerField.value === "true") {
f2();
updateOpenerField.value = "false";
}
// for the 2nd approach just do nothing
function f2() {
alert("Hello, opener!");
}
</script>
</form>
protected void ClickMeButton_OnClick(object sender, EventArgs e)
{
//1st approach
UpdateOpenerHiddenField.Value = "true";
// 2nd approach
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2();", true);
}
No, you can't run server side code (OnClick event handler) before client side. OnCLientClick event was added to perform some validation before post back. There is only one way to do it - update the f2 method and post data on server via ajax
You can put your javascript inside a PlaceHolder tag which you make visible in your server-side OnClick handler.
aspx code:
<asp:PlaceHolder id="refreshScript" visible="false" runat="server">
window.opener.location.href = window.opener.location.href;
window.close();
</asp:PlaceHolder
cs code:
protected void button_Click(Object sender, EventArgs e) {
// do whatever
refreshScript.Visible = true;
}

doPostBack from C# with JavaScript

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

Categories