Call Javascript function multiple times from code behind - javascript

I have the following button event handler in C#. I would like to call the same javascript function with different paramater.
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
string script = String.Format("test({0},{1})", i.ToString(), i.ToString() + 1);
this.Page.ClientScript.RegisterStartupScript(this.GetType(),
"testFunction", script, true);
}
}

define your js method like:
<script type="text/javascript">
function UpdateTime(time) {
document.getElementById("<%=lblTime.ClientID %>").innerHTML = time;
}
and then in your code behind, use:
protected void UpdateTime(object sender, EventArgs e)
{
string time = DateTime.Now.ToString("hh:mm:ss tt");
string script = "window.onload = function() { UpdateTime('" + time + "'); };";
ClientScript.RegisterStartupScript(this.GetType(), "UpdateTime", script, true);
}
Source and demo here

Related

How can I call a javascript function from server side

I try to call a javascript function from an other c# function but I have an error in my console
Uncaught ReferenceError: updateState is not defined
.ascx file
<script>
function updateState(){
console.log("test")
}
</script>
<button runat="server" ID="Btn_Modify_state" onserverclick="Btn_Modify_state_Click">
<i class="fas fa-edit"></i>
</button>
.ascx.cs file
protected void Btn_Modify_state_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "updateState();", true);
}
I don't know how to resolve that issue someone have any idea ?
You may have forgotten to register the script. Try this different approach instead.
<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client script on the page.
String csName = "updateState";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
// If not, redefine your script
var csText = $"
<script type=\"text/javascript\">
function updateState(){
console.log("test")
}
</script>";
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
}
</script>
Source : https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.clientscriptmanager.registerclientscriptblock?view=netframework-4.8
The solution was to do that :
.ascx.cs
protected void Btn_Modify_state_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "script", "<script type='text/javascript'>updateState();</script>");
}

Asp.net JavaScript OnClick not working

What I'm trying to do is, when I click on the button it should show an alert box.
Here is the code.
protected void btnAdd_Click(object sender, EventArgs e)
{
string script = "<script type=\"text/javascript\">alert('abc 1');
</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert 1",
script);
Response.Redirect("~/Index.aspx");
}
It is working perfectly but when I put this same code in another page it does not work.
what are the things I have to look into? any suggestion please?
move your js code to client side
<asp:Button ID="btnAdd" OnClientClick="alert('alert');" OnClick="btnAdd_Click" runat="server"/>
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("~/Index.aspx");
}
May be you can try this - syntax may be wrong -
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("~/Index.aspx?Issuccess=1");
}
index.aspx page -
protected void Page_Load()
{
if(Request.QueryString["Issuccess"] != null && Convert.ToInt32(Request.QueryString["Issuccess"]) == 1)
{
string script = "<script type=\"text/javascript\">alert('abc 1');
</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert 1",
script);
}
}
Pass the last Parameter either True or False in ClientScript.RegisterScript and better you pass the alert message in this way.
Like This
protected void btnAdd_Click(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('abc 1');",true);
Response.Redirect("~/Index.aspx");
}

How to pass String Argument to javascript function

This is my front-end:
ImageButton Details = (ImageButton)e.Row.FindControl("iBtnDetails");//take lable id
String strApplication1 = Details.CommandArgument.ToString();
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes.Add("onClick", "SelectRow()");
This is my back-end:
<script type="text/javascript">
function SelectRow() {
var strApplication1 = '<%=strApplication1%>'
if (strApplication1 == "IT Application Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "IT Account Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Change Control Management")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Backup & Restore")
{
window.open('http://.aspx', '_blank');
}
}
</script>
I want to pass String Argument to javascript function, but I got error that strApplication1 doesn't exist in the current context.
You need to make strApplication1 a public property on your page class. Currently, it is just an internal variable.
Something like:
public partial class YourPage : System.Web.UI.Page
{
public string strApplication1 {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
//Your page logic
}
//Looks like you set the variable in an onDatabound or similar.
//So use this where you currently set the variable
strApplication1 = Details.CommandArgument.ToString();
}

Call Javascript function and pass value from C#

in HTML:
<script type="text/javascript">
function removeIndustry(item)
{
confirm(item);
}
</script>
in C#:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "<a href='javascript:removeIndustry('IndustryNameHere')'><i class='icon-remove'></i></a>Click";
}
The code is not working if I put any strings like 'IndustryNameHere' in that function. Without any values, it is working fine. Anyone please help me fix this error. Thanks a lot.
Try to escape quotes with \:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "<i class='icon-remove'></i>Click";
}

Receive function parameters in javascript?

Is possible receive the parameters that were sent from the
IFrame code behind (id and pTmp) the javascript popup then send them to the page parent
Code IFrame
protected void btnConfirm_Click(object sender, EventArgs e)
{
EDPBLL = new EDPLogic();
int id = EDPBLL.Add(Convert.ToInt32(Request.QueryString["EDP"]), Convert.ToInt32(Session["userId"]), DateTime.Now, Convert.ToInt32(ddlPrensa.SelectedValue));
string numeroEDP = EDPBLL.generarNumeroEDP(id);
EDPBLL.UpdateEdpCode(id, numeroEDP);
Session["pEDPId"] = id;
Session["numeroEDP"] = numeroEDP;
int pTmp = 4;
ScriptManager.RegisterStartupScript(Page, GetType(), "Popup", "<script>Popup('"+id+"','"+pTmp+"')</script>", false);
}
The script simulates a click event of parent window
Code JavaScript .aspx
<script type="text/javascript">
function Popup() {
$("#MainContent_btnPrueba", window.parent.document).trigger("click");
}
</script>
Use this
<script type="text/javascript">
function Popup(var1, var2) {
$("#MainContent_btnPrueba", window.parent.document).trigger("click");
}
</script>

Categories