How to call onclientclick after onclick - c#

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");

Related

asp.net C# update textbox value without refresh

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

set the asp:textbox val() in jQuery and get the Text of the same on the server side code

I have successfully set the text of asp:textbox using jQuery val() function, now I want the same value of the textbox on click of asp:button on the server side code.
$("#textboxId").val('some text');
protected void button_Click(object sender, EventArgs e)
{
// getTheText is blank
string getTheText = textboxId.Text.Trim();
}
<script type="text/javascript">
$(document).ready(function () {
$('#<%= TextBox1.ClientID %>').val("my value");
});
</script>
and in code behind on button click use
protected void Button1_Click(object sender, EventArgs e)
{
var value = TextBox1.Text;
}
this will work. it work for me i test it.
I also had the same problem and finally found a solution.
string getheText =Page.Request.Form["textboxId"].ToString().Trim();
But be careful if you use "Content" in master page the id must be like that
string gettheText = Page.Request.Form["ctl00$ContentPlaceHolder1$textboxId"].ToString().Trim();
if your textbox is an aspx server control then you can directly set Text by using
textboxId.Text = "Some Value";

Opening URL using an ImageButton

using asp.net | C#
I want my ImageButton to open a URL when I click it. I finally have my Image loading and it clicks but when I click it nothing happens. Here is the code I have so far:
aspx page
<asp:ImageButton ID="Button1" runat="server" ImageUrl="~/images/button.gif"
onclick="Open_Click"></asp:ImageButton>
aspx.cs page
protected void Open_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
try
{
System.Diagnostics.Process.Start("http://www.website.com");
}
catch { }
}
You want to do a redirect, not start a process. Try this:
protected void Open_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
try
{
Response.Redirect("http://www.website.com");
}
catch { }
}
Additionally, you could just set the PostBackUrl attribute on the control and have no need for a server side event.
You can do it on the client-side:
This will open in another window:
<asp:ImageButton OnClientClick="window.open('/xxx/xxx.aspx');
OR this will open in same window, javascript needs to return false so server code won't run:
<script>
function ReDirect() {
location.href = '/xxx/xxx.aspx';
return false;
}
</script>
asp:ImageButton OnClientClick="javascript:return(ReDirect());" />

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.

Confirmation message box in webapplication

Am using the below message box in asp.net web application. Now i want to convert this message box as a confirmation message box and do something when it is true else means reject the application.
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('Are you sure, you want to apply?');</script>", false);
I think you are going about this the wrong way. You should display this confirmation before posting back, and then only post back if they choose to "Apply".
Using ASP.NET web controls, the Button control has an OnClientClick property which can be used to call javascript prior to Http POST:
You could do something like this:
<asp:button id="btn"
runat="server"
Text="Apply"
OnClientClick="return confirm('Are you sure you wish to apply?');"
OnClick="btn_Click" />
register script bellow instead of alert
<script type="text/javascript">
var r=confirm("Are you sure you are sure?")
if (r==true)
{
//You pressed OK!
}
else
{
//You pressed Cancel!
}
</script>
The javascript equivalent to a confirmation box is the confirm() method. This method returns a true or false value depending on the user's "OK" or "Cancel" button response.
Usage:
var confirmed = confirm('Are you sure?','Are you sure you want to delete this item?');
if(confirmed){
//do something
} else {
//do something else
}
Try this
Add this on your cs file to display a confirm instead of alert
string confirm =
"if(confirm('Are you surely want to do this ??')) __doPostBack('', 'confirmed');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", confirm, true);
Add this on same page to check when user is coming from that confirmation box
protected void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
if (string.Equals("confirmed",
parameter,
StringComparison.InvariantCultureIgnoreCase))
{
// Call your server side method here
}
}
For this I used __doPostBack you can learn more about it from here.
Hope it'll help you
private void showMessage(string msg){
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('"+ msg +"');</script>", false);
protected void BtnReg_Click(object sender, EventArgs e)
{
OracleHelper.OracleDBOpen();
object flag = OracleHelper.OracleExecuteScalar("your select Query ");
if (flag == null)
{
showMessage("Failed !!! ");
}
else
{
string reg = String.Format("your Insert Query ");
showMessage("successfuly");
OracleHelper.OracleExecuteNonQuery(reg);
}
OracleHelper.OracleDBClose();
}
}
To do this completely within C#, you can try this:
protected override void OnInit(EventArgs e)
{
AddConfirmationButton();
base.OnInit(e);
}
private void AddConfirmationButton()
{
Button confirmButton = new Button();
confirmButton.Text = "Action Foo";
string confirmationMessage = "Are you sure you wish to do action Foo?";
confirmButton.OnClientClick = "return confirm('" + confirmationMessage + "');";
confirmButton.Command += confirmButton_Command;
Controls.Add(confirmButton);
}
void confirmationMessage_Command(object sender, CommandEventArgs e)
{
DoActionFoo(); //work your magic here.
}
This presents and "OK/Cancel" dialog box to the user from the webpage. If the user clicks 'ok', the function from the command Event fires. If the user clicks 'cancel', nothing happens.
ScriptManager.RegisterStartupScript(page,this.GetType(), "temp","javascript:calopen();
",true);
function calopen()
{
if (confirm("Are you sure?"+'\n'+"Are you want to delete"))
{
enter code here
}
else
{
return false;
}
}
try this code check on OnClientClick event when user click on button
<script type="text/javascript">
function check()
{
var chk =confirm("Are you sure you are sure?")
if (chk==true)
{
// try you want
}
else
{
// try you do not want
}
return true;
}
</script>
<asp:button id="Button1"
runat="server"
Text="Button1"
OnClientClick="return check();"/>

Categories

Resources