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.
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
In my javascript file, I got an ajax to get all list and iterate these data and append <a id='userID' class='btn'>Assign ID<> to my list.
So, how do a add postback to these anchor and redirect it inside my method in the server. Below is my code but didn't work. When I click the achor button, it just redirect/refresh to the same page without doing any changes and didn't show the text.
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick='javascript:__doPostBack('uniqueID','')'>Assign ID</a>
protected void Action_assignID(object sender, EventArgs e)
{
// assign ID action
Response.Write("Pass");
}
You should be changed your button to:
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick="javascript:__doPostBack('uniqueID','Assign ID')">Assign ID</a>
And it's a good idea to implement the IPostBackEventHandler interface in your codebehind as below:
public partial class WebForm : Page, IPostBackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
public void RaisePostBackEvent(string eventArgument)
{
// do somethings at here
}
}
Hope this help!
The __doPostBack method really doesn't do anything special except, well... perform a POST operation back to the same page with two specific form arguments.
The first parameter is the __EVENTTARGET and the second parameter is the __EVENTARGUMENT.
The magic all happens in ASP.Net where it automagically wires up your controls to event handlers, but since you are creating these entirely in JavaScript the server doesn't know that those controls exist.
However, you can manually grab these values and do something with them.
//Client Side JavaScript:
__doPostBack('my-event', '42');
//Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var target = Request.Params["__EVENTTARGET"];
var args = Request.Params["__EVENTARGUMENT"];
Target.Text = target; // 'my-event'
Argument.Text = args; // '42'
}
}
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've got this button
<asp:Button runat="server" ID="btnReviewDocs" CssClass="btnReviewDocs" data-theme="b"
Text="Review Documents" OnClick="btnReviewDocs_Click" OnClientClick="clickHyperlink();"/>
And in 'OnClick' event I'm assembling an URL that I need to set to asp:Hyperlink and at the end of the 'OnClick' I'm setting this URL to the 'NavigateURL' propery of the 'asp:Hyperlink'. Once the 'asp:Hyperlink' has the correct URL I need to call the 'clickHyperlink()' function.
function clickHyperlink() {
var href = $('#hlnkID').attr('href');
if (typeof href !== "undefined") {
$.mobile.showPageLoadingMsg();
window.location.href = href;
}
}
But the 'OnClientClick' event is executed always before the 'OnClick'. Any suggestions for a workaround?
I'm doing all this stuff, because I've got problems with JQuery Mobile and 'Response.Redirect(url);' is changing the page, but not the URL.
I believe that you don't really need to involve the Hyperlink control in the JS part.
Modify your JS function and remove the OnClientClick attribute from the btnReviewDocs button:
<script type="text/javascript">
function clickHyperlink(href) {
$.mobile.showPageLoadingMsg();
window.location.href = href;
}
</script>
On the server, in the btnReviewDocs_Click method:
protected void btnReviewDocs_Click(object sender, EventArgs e)
{
// TODO: set the url, maybe append some params to the
// hlnkID.NavigateUrl value
var url = "http://stackoverflow.com/";
ClientScript.RegisterStartupScript(Page.GetType(),
"clickHyperlink",
"clickHyperlink('" + url + "');",
true);
}
Use the RegisterStartupScript in the ClientScript object to run the code after postback--->
protected void btn_Click(object sender, EventArgs e)
{
//some code
this.ClientScript.RegisterStartupScript(this.GetType(), "clintClick", "clickHyperlink", true);
}
try this
protected void btnReviewDocs_Click(object sender, EventArgs e)
{
//something doing here
Page.ClientScript.RegisterStartupScript(this.GetType(), "test", "<script type='text/javascript'>clickHyperlink()</script>");//call javascript function
}
The answer is mentioned by #Alex Filipovici.
But first you should ask yourself do you really need to go back to the client side to do a redirect ?
Why not call :
Response.Redirect("MyURL");
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')"