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')"
Related
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
This is my C# building the html. I tried to change the OnServerClick with the onclick and onclientclick with the result that:
Onserverclick does not fire anything
onclick gives me an exception
that tells me that the method is not defined
onclientclick does not
fire nothing
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/img/"));
List<ListItem> files = new List<ListItem>();
tabellaDownload.InnerHtml += "<table>";
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
// tabellaDownload.InnerHtml += "<tr><td OnServerClick = 'DownloadFile' runat='server'>" + Path.GetFileName(filePath) + "<td></tr>";
tabellaDownload.InnerHtml += "<input type='button' runat='server' OnServerClick='DownloadFile' value='asd' />";
}
tabellaDownload.InnerHtml += "</table>";
string asd = "";
}
}
protected void DownloadFile(object sender, EventArgs e)
{
//do something
}
What are you trying to do is to add a control to your form so if you want to do it dynamically you need to do something like this:
protected void Page_Load(object sender, EventArgs e)
{
HtmlButton b = new HtmlButton
b.ServerClick += MyEvent;
tabellaDownload.Controls.Add(b);
/* a table control doesn't accept a btn as child, you need to the exact td cell where insert the button*/
}
protected void MyEvent(object sender, EventArgs e)
{
}
Everything in web form is a control included in a controls collection.
The Aspx files contains in forms of mark-up a mix of html and server directives(you can notice the difference by the runat attribute which marks the server directives), the server side directives are rendered as html mark-up to send to the browser, in a way similar to this:
<input name="ctl00$MainContent$ctl00" onclick="__doPostBack('ctl00$MainContent$ctl00','')" type="button">
When you assign a string to InnerHtml attribute of a control, you are sending exactly what you want to render client side but there is no one html specific(or ecma script specific) that defines the runat attribute!
I'm using a Repeater, there is a button for each item. When I click on one of these buttons asp.net returns me the following error:
Invalid postback or callback argument
But when I add the Page directive EnableEventValidation = "false" on my page, no error but does not fire my event.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
Customer activeCustomer = (Customer)Session["user"];
Response.Write("Welcome " + activeCustomer.FirstName + " " + activeCustomer.LastName + " | Offer count:" + activeCustomer.OfferLimit);
if (!IsPostBack)
{
ProdRepeater.DataSource = CampaignDataProcess.getDailyCampaign();
ProdRepeater.DataBind();
}
}
else
{
Response.Redirect("Login.aspx");
}
}
I have already tried if(!IsPostBack) in page load.
How can this be resolved?
if you are using more than form in your aspx file, you can not use your events. I had a problem like your and i solved my problem deleting that form tags.
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.
I have a simple email form written in ASP.NET with the logic in the codebehind file. It's all in C# (the logic that is...). Anyways, on page load I have the following:
protected void Page_Load(object sender, EventArgs e)
{
RequestorName.Text = Request.Form["UserName"].ToString();
RequestorTitle.Text = Request.Form["JobTitle"].ToString();
RequestorEmail.Text = Request.Form["Email"].ToString();
RequestorPhone.Text = Request.Form["Phone"].ToString();
RequestorAddress1.Text = Request.Form["Address"].ToString();
RequestorAddress2.Text = Request.Form["City"].ToString() + " " + Request.Form["State"].ToString() + ", " + Request.Form["Zip"].ToString();
}
This works great as it pulls the users information into a few fields so they don't have to fill everything out by hand.
My other 2 methods in the code behind:
protected void SubmitForm_Click(object sender, EventArgs e)
{
SendEmail();
}
protected void SendEmail()
{
try
{
//compose email and send
}
catch (Exception ex)
{
ErrorMessage.Text = "Error: " + ex.ToString();
}
}
On my form page the button code is this:
<center>
<asp:Button runat="server" Text="Submit" ID="Submit" OnClick="SubmitForm_Click" class="button red" />
</center>
The error occurs when I click the send button on the form that generates the email and sends it. I can remove the Page_Load code and works great but I'd like to keep it there so the user doesn't have to fill out as much information.
I've used my Google Fu and read a ton of threads/articles but can't seem to find the solution...
Thanks for any assistance.
Add check for IsPostBack:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RequestorName.Text = Request.Form["UserName"].ToString();
RequestorTitle.Text = Request.Form["JobTitle"].ToString();
RequestorEmail.Text = Request.Form["Email"].ToString();
RequestorPhone.Text = Request.Form["Phone"].ToString();
RequestorAddress1.Text = Request.Form["Address"].ToString();
RequestorAddress2.Text = Request.Form["City"].ToString() + " " + Request.Form["State"].ToString() + ", " + Request.Form["Zip"].ToString();
}
}
Have you tried adding if (Page.IsPostBack == false) to your Page_Load event?
I assume that the Request.Form code comes from fields that the user has filled out, but without seeing the rest of your markup, I'm not sure why you'd have to re-assign values from the form to what appear to be other fields on the form.
Where specifically is the error occurring?
From your code, I'm assuming that you are posting to your email form from another page and passing the parameters across.
If that's the case then assuming your .Text are the page controls then you should look at containing the control fillers in an If(!IsPostback) {...} for the first loading of the page only. Then your email code can read from the local controls.
My guess is that the "Request.Form[..." items are probably the ones kicking back error on postback.
HTH
Dave