asp.net C# update textbox value without refresh - c#

I have a website where there are two pages, page1 contain textbox and button1,
if I cliked button1 it will open page2 which contain button2,
if I cliked button2 it will assign value from page2 to the textbox in page1
but the problem is the value will display in the textbox after I refresh page1,
and my question is how I can update textbox value directly without refresh in page1 after I click button2 in page2 like this:
here is my code:
page1 aspx.cs:
<script type="text/javascript">
function openPopup() {
window.open("page2.aspx", "_blank", "WIDTH=1080,HEIGHT=790,scrollbars=no, menubar=no,resizable=yes,directories=no,location=no");
}
<asp:button text="clik" id="button1" runat="server" onclientclick="return openPopup()" xmlns:asp="#unknown" style="margin-right:30%" />
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userID"] != null)
{
txtbox.Text = HttpContext.Current.Session["userID"].ToString();
}
}
page2:
protected void button2(object sender, EventArgs e)
{
Session["userID"] = row.Cells[0].Text;
}

we can do this in following way:
create a javascript function on page 2, that refresh textbox1 on
page 1.
on button2 click from page 2, using scriptmanager, call
the function created in step 1 with require param.
So, basically you code be like:
// place this in page2.aspx
// javascript function to update text box in page 1;
function UpdateParentText(value){
if(typeof(value) != undefined){
window.opener.document.getElementById("TextBox1").value=value;
}
}
//2. code behind call to the javascript function from page2.cs
protected void button2(object sender, EventArgs e)
{
// code behind call to the javascript function.
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "MyScript", "UpdateParentText('" + row.Cells[0].Text + "'", true);
}
If you are not using AJAX, then use this:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", "UpdateParentText('" + row.Cells[0].Text + "'", true);

You may use:
window.postMessage() — to send the message
window.addEventListener(“message”,callback) — to receive and process the message
See sample here.

thanks everyone I solve it by using session with javascript

Related

asp.net server side buttons clicks programatically

i have 2 server side asp.net buttons , i need to automate the buttons clicks.
i.e. After page_load, i need to click button1 and after its results are shown on the page, wait for 10 seconds and click button2 .
i tried the following sample code
protected void Page_Load(object sender, EventArgs e)
{
Button1_Click(Button1, null);
Thread.Sleep(10000);
Button2_Click(Button2, null);
}
protected void Button1_Click(object sender, EventArgs e)
{
changeLabel.Text = "Button1";
}
protected void Button2_Click(object sender, EventArgs e)
{
changeLabel.Text = "Button2";
}
}
i had 2 obeservations (maybe useful):
always Button2_Click(Button2, null); event is the latest when the page is fully loaded (which is obvious).
Page_Load(object sender, EventArgs e) doesnot
hit atall when programatically clicked the button.
Any idea how to achieve the solution.
What you are doing in your example is to call the handlers of button1 and button2's click events, that is not the same as having the user click the buttons, and for the form to postback to the server.
If you want the buttons to click them selves and having the post back to the server you need to add javascript that clicks the buttons for you.
If you want a javascript which hits a button for you after X seconds, i would do something like this:
in your aspx page:
<asp:button ID="Button1" runat="server" ClientIDMode="Static" OnClick="Button1_Click">
</asp:button>
in your javascript files or some block on your page:
<script type="text/javascript">
setTimeout(function(){
document.getElementById("Button1").click();
}, 10*1000); // 10 seconds
</script>
Important to note here is that you have to either set ClientIDMode="Static" on your button, otherwise it might have a very obscure name if you are using master pages, or you can do:
<script type="text/javascript">
setTimeout(function(){
document.getElementById("<%= Button1.ClientID %>").click();
}, 10*1000); // 10 seconds
</script>
if you have the javascript in your .aspx file rather then its own .js file.
ps: if you do Thread.Sleep(X) in an aspx page, you will only make the users browser wait for the X milliseconds more for the page to load, code run before the sleep will not be submitet to the clients browser in the way i think you want it to do.
Button_Click is server event, when invoked from client, browser post the relavent data to server and request of new page content, at that time Page_load is invoked.
if you want to do some thing, encapsulate action to some method and call that method in pre-render. Or other wise, use JavaScript.
protected void Page_PreRender(object sender, EventArgs e)
{
UpdateButton1()
Thread.Sleep(10000); // no need to put sleep
UpdateButton2();
}
protected void Button1_Click(object sender, EventArgs e)
{
UpdateButton1();
}
protected void UpdateButton1()
{
changeLabel.Text = "Button1";
}

clear the textbox after redirect to a download page

i have 2 pages. main.aspx and download.aspx
page_load at download.aspx is to download a file
textbox and download button at main.aspx
-no function at page_load
-button redirect to download.aspx
-textbox cannot be left blank.
after i filled the textbox and press the button, the page remain at main.aspx and file is downloaded from download.aspx.
now the problem is, how can i clear the textbox after i press the download button?
I tried:
this.Textbox1.Text = ""; before and after the redirect.
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "document.getElementById('Textbox1').value =''", true); before and after the redirect
Response.Redirect("main.aspx); after Response.Redirect("download.aspx");
onclientclick = "validation()"
function validation() {
document.getElementById('TextBox1').value= "";
}
remember i have the validation, so 4. cannot work.
5.
OnClientClick ="document.forms[0].target = '_blank';"/>
Response.Redirect(”download.aspx”,false);
Textbox1.Text="";
6. Textbox1.EnableViewState = false;
7.button clicked, redirect to main2.aspx, pageload at main2.aspx redirect to download.aspx. but after i clicked the button at main.aspx, the file is downloaded, but the page is still remains at main.aspx.
none of the method above is working, what else can i try? and what is the problem? why the textbox cannot set to blank?
main.aspx
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.TextBox1.Text = "";
Response.Redirect("download.aspx");
this.TextBox1.Text = "";
}
download.aspx
protected void Page_Load(object sender, EventArgs e)
{
string reportPath = "C:\\form.pdf";
Response.ContentType = "appplication/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=form.pdf");
Response.TransmitFile(reportPath);
Response.End();
}
Try javascript to clear the textbox value
I think,you can use the get method to download.
the button's onClientClick code:
function doGet(){
var txt=document.getElementById('<%=this.TextBox1.ClientID %>').value;
window.open ('download.aspx?file='+txt);
document.getElementById('<%=this.TextBox1.ClientID %>').value='';
}
and in the download.aspx.cs
you can get the value from the main.aspx,like
string file=this.Request.QueryString["file"];
Don't use the ReDirect method to request the download page.

Call Javascript function with parameters from C# Page .aspx

I have RegisterClientScriptBlock which is written inside page load of .aspx file protected void Page_Load(object sender, EventArgs e)
The Script actually gets ID From URL and then Pass it to openticketPageLoad() function of javascript.
But it is not getting into openticketPageLoad() function. But .aspx page is loading.
openTickets.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "openTicketsScript", "<script type=\'type/javascript\'>$(document).ready(function(){openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");});</script>".ToString(), true);
}
}
Inside my javascript file
function openticketPageLoad(b)
{
alert(b); //No alert window coming.
}
See the documentation here: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerclientscriptblock.aspx
The last parameter is a boolean that specifies whether ASP.net should generate Script tags. As you already specify them I expect if you look at your source you are generating nested script tags.
Can you try the following code:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(),
"openTicketsScript", string.Format("openticketPageLoad({0});", Request.QueryString["ID"]), true);
}
}
Try this
Page.ClientScript.RegisterStartupScript(this.GetType(), "openTicketsScript", "<script type=\'type/javascript\'>$(document).ready(function(){openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");});</script>".ToString(), true);
Perhaps you could do is assign the call to your javascript function direct in the load event of the body of the page. To assign the load function of the body from a content page can do the following:
HtmlGenericControl body = this.Master.FindControl("body") as HtmlGenericControl;
body.Attributes.Add("onLoad", "openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");");
And in the master page add the runat="server" to the body element:
<body id="body" runat="server">
I hope this helps.

C# / asp.net global Variables?

I have two buttons with on click functions
The 1st one gets assigned a variable when Clicked.
How do I get my second button to get the variable from the 1st button when I click button 2?
It doesn't seem to work. As the second button doesn't recognise the Variable.
Thanks
EDIT:
Just to clarify My code is generating a pdf. button 1 selects the url of the template to use. and in button 2 (the one generating the pdf) I want it to get the variable set from button 1 so it knows what template to use.
EDIT 2:
My code does work but only when I'm not using the ajax update panel. it seems that the variable I'm trying to set doesn't get set with AJAX
Your Button have Id, you get this button with his Id
Nota : You can add runat="server" in order to visualize in server side
<asp:Button id="Button1"
Text="Click "
OnClick="Btn1_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Click "
OnClick="Btn2_Click"
runat="server"/>
void Btn2_Click(Object sender, EventArgs e)
{
Button1.Text = "test after click on button 2";
Template = ...;//Set your value
}
void Btn1_Click(Object sender, EventArgs e)
{
Button2.Text = "test after click on button 1";
//Here you can get your value after post.
var result = Template;
}
It's not subject but in delegate you can also get objet button by passing on sender argument.
var button = sender as Button; //You get button who raise event
In order to manage Template Path property.
public string Template
{
get
{
if(ViewState["Template"] != null)
{
return (string)ViewState["Template"];
}
}
set{ViewState["Template"] = value;}
}
i guess you are looking at accessing value of a variable inside the click event of button2 for which the value is set in the button1 click event ?
private string myPrivateString = "";
void Page_Load()//Not sure of correct method signature
{
if(Page.IsPostBack)
{
myPrivateString = Session["myPrivateString"];
}
}
void Button1_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
myPrivateString = "Value Set From Button 1";
Session["myPrivateString"] = myPrivateString;
}
void Button2_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
//Accessing myPrivateString here without setting value from session
//will return empty string as after PostBack its a new page thats rendered.
myPrivateString = Session["myPrivateString"]; // Or do it in the Page_Load event
}
I guess now you can get the value of inside the button2 click event.
Also read about ASP.NET Page lifecycle and how client side events like button clicks are handled by the ASP.NET framework.

Messagebox from master page

How to display a messagebox from the ASP.net(C#) master page itself. I mean when a link button on the master page is clicked a message box is to be displayed. i've tried calling the following method with no result.
public void MessageBox(string message, Page page)
{
if (!string.IsNullOrEmpty(message))
{
Label lbl = new Label();
lbl.Text = "<script type=\"text/javascript\" language=\"javascript\">"
+ "alert('" + message + "'); " + "</script>";
page.Controls.Add(lbl);
}
}
Either register the OnClientClick to the LinkButton, then the alert will be shown before the postback, or register the alert-script in the Click-Event handler during postback, so that the alert will be shown as soon as the page is rendered to the client the next time:
protected void Page_Load(object sender, System.EventArgs e)
{
MyButton.OnClientClick = "alert('MyButton clicked!');";
}
protected void MyButton_Click(object sender, System.EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('MyButton clicked!');", true);
}
I just put your code into a page and it worked with no problem. It was not a master page but I see no difference in why it wouldn't work in a master page just as well. Here is the code that worked for me:
The linkbutton in the page:
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
The code behind:
public void MessageBox(string message, Page page)
{
if (!string.IsNullOrEmpty(message))
{
Label lbl = new Label();
lbl.Text = "<script type=\"text/javascript\" language=\"javascript\">" + "alert('" + message + "'); " + "</script>";
page.Controls.Add(lbl);
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
MessageBox("test", Page);
}
You should use ClientScriptManager.RegisterClientScriptBlock to add scripts to the page instead of literal controls with javascript values.
I'd suggest a base class for your master page, something like:
public sealed class MasterPageBase : MasterPage
{
protected void AddAlertMessage(string Message)
{
var script = String.Format("alert('{0}');", Message);
this.Page.ClientScript
.RegisterStartupScript(this.GetType(),"PageAlertMessage",script,true);
}
}
Now set this as your base across your master pages, and you can call:
protected void LinkButton1_Click(object sender, EventArgs e)
{
this.AddAlertMessage("Hello");
}
The main benifit is that the script details are abstracted away, and you can easily make global changes to them (switching to a Growl Style alert for instance) without making many page edits.
On the page load of master page write the following code
lnkButton.Attributes.Add("onclick","alert('message');");
The following code worked for me.
linkbutton1.OnClientClick ="javascript:alert('Hello')"

Categories

Resources