click() Event in javascript with a PARAM? - javascript

I'm using the event click() to call a method in Code Behind, like this:
HTML
<asp:button bordercolor="White" id="btnAddGS" onclick="AddGSBandeira" runat="server">
JAVASCRIPT
$("#ctl00_ContentPlaceHolder1_btnAddGS").click();
C#
public void AddGSBandeira(object sender, EventArgs e)
{
}
Its work normally, but I need to pass a param in the javascript call, like this:
$("#ctl00_ContentPlaceHolder1_btnAddGS").click("param");
But I do not know how this works ...can anybody help?

The best thing to do is create a hidden control and populate it's value with JavasScript on the click event. Your code behind will be able to access that value on your postback (AJAX or otherwise).
Markup
<asp:HiddenField ID="myHiddenField" runat="server" />
<asp:button bordercolor="White" id="btnAddGS"
onclick="AddGSBandeira"
onclientclick="SetHiddenValue()" runat="server">
JavaScript
function SetHiddenValue()
{
document.getElementById("<%=myHiddenField.ClientID%>").value = "[Your value here]";
}
C#
public void AddGSBandeira(object sender, EventArgs e){}
{
var jsVal = myHiddenField.Value;
}

You can do this with trigger.
http://api.jquery.com/trigger/
$("#ctl00_ContentPlaceHolder1_btnAddGS").trigger("click",["param"]);
I believe the 2nd parameter to trigger should be an array of arguments to pass to the function.

Related

How do I call a C# method using JavaScript in .NET Framework 4.7.2?

Whenever the textbox value changes a C# method should be called. The textbox uses a calendar validator so when a user changes the date it should count as a value change. The date can be changed by clicking on a new date or typing it in. Typing it in can possibly call the method multiple times which is fine. How can I activate a C# method whenever a textbox value is changed using JavaScript in .NET Framework 4.7.2?
.ascx file:
<script type="text/javascript">
$(document).ready(function () {
$("#textBox1).change(function () {
// How can I call the buttonClick method?
}
});
</script>
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="date" runat="server" ControlToValidate="textBox1"
ErrorMessage="Date Required" CssClass="field-validation-error"></asp:RequiredFieldValidator>
<ajax:CalendarExtender ID="ceDate" runat="server" TargetControlID="textBox1" />
.ascx.cs file:
protected void buttonClick(object sender, EventArgs e)
{
//...
}
I tried doing this without JavaScript. There is an OnTextChanged event listener that should call the buttonClick method. This has not been working for me. Clicking on a new date or typing in the textbox doesn't trigger the method. It only seems to trigger when I press the 'Enter' key. The event listener should not depend on the 'Enter' key being pressed.
.ascx file:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick"></asp:TextBox>
<asp:RequiredFieldValidator ID="date" runat="server" ControlToValidate="textBox1"
ErrorMessage="Required" CssClass="field-validation-error"></asp:RequiredFieldValidator>
<ajax:CalendarExtender ID="ceDate" runat="server" TargetControlID="textBox1" />
Method 1:
<script type="text/javascript">
$(document).ready(function () {
$("#textBox1").change(function () {
<%= Page.ClientScript.GetPostBackEventReference(textBox1, "") %>
}
});
</script>
But take care that under certain circumstances, the id value of the text box control will not necessarily be the same as the ID (name) of the textbox control on the server side. One way to make sure that your jQuery selector uses the correct value for the id of the textbox control is to use the ClientID property of the server-side object, like so:
<script type="text/javascript">
$(document).ready(function () {
$("#<%= textBox1.ClientID %>").change(function () {
<%= Page.ClientScript.GetPostBackEventReference(textBox1, "") %>
}
});
</script>
Or if you don't want to bother with using the ClientID property, then you can set the value of ClientIDMode attribute on the mark-up of the control to Static, then the id on the server and client will always be the same, like so:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick" ClientIDMode="Static"></asp:TextBox>
However, it is not advisable to use ClientIDMode="Static" within custom user controls, since you could end up with multiple elements with the same ID on the client when the control is used multiple times on the same page.
Method 2:
It is also possible to achieve all this without using JavaScript.
The buttonClick server-side event handler will not be called until the form is posted back to the server-side.
One way to automatically do a post-back to the server whenever the text is changed is by adding the AutoPostBack="true" attribute to the mark-up of the textBox1 control:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick" AutoPostBack="true"></asp:TextBox>
Side-note: Remember, doing a post-back will cause the whole page/control life-cycle to be executed, even if your controls are within an <asp:UpdatePanel>...</asp:UpdatePanel> block (for asynchronous/ajax updates), so things like the Page_Load function will be run every time there is a post-back. If you have initialization code within such functions and you don't want to re-initialize on every post-back, just check that the Request is not post-back before running initialization code, i.e:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// initialization
}
}

Server tag not well formed for ASP DropDownList for ItemTemplate

<asp:TemplateField HeaderText="Company Membership">
<ItemTemplate>
<asp:DropDownList id="ddlCompanyMembership" runat="server" class="form-control" onchange="verifyUser('<%# ((DataRowView)Container.DataItem)["CCMP_CODE"].ToString() %>');" />
</ItemTemplate>
</asp:TemplateField>
I can't seem to build this properly. It's suppose to call a Javascript function and pass the value to the function. But it shows Server tag not well formed error.
I've tried looking for solutions, some said the quotes and double quotes do matter. But I've tried everything and nothing's working.
You may consider binding onchange event on the server side by handling GridView's RowDataBound event. You will be able to bind your event as follows which is more convenient in my opinion.
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find your drop down list
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlCompanyMembership");
// Add onchange event as attribute
ddl.Attributes["onchange"] = "verifyUser('your logic');";
}
}
onchange="verifyUser('<%# DataBinder.Eval(Container.DataItem, "CCMP_CODE").ToString()%>');"
above code helps you to make it working.

How to call javascript function and code behind using button

How to call javascript function and code behind function using button?
<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return javascriptfunction();" runat="server">
</asp:button>
I tried like this too. but no response.
<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return true;" runat="server">
</asp:button>
even, javascript function return true, its not calling codebehind function. May i know reason?
The code should be something like this -
JavaScript:
<script>
function save()
{
return confirm('Are you sure you want to continue?');
}
</script>
ASPX:
<asp:Button ID="btnSave" OnClick="btnSave_Click" OnClientClick="return save();"
runat="server" />
C# CodeBehind:
protected void btnSave_Click(object sender, EventArgs e)
{
// Do something
}
It basically call JavaScript function before posting back to server. Whether post back to server or not is depending upon the return value from JavaScript function.
Button control's OnClick is an server side event so you need to attach to server side click event.
The best way I have found to do this is from code behind using RegisterStartupScript
ScriptManager.RegisterStartupScript(this, this.GetType(), "name", "javascriptfunction();", true);

Call JavaScript function (in aspx) on aspx.cs using a button

I have this aspx:
<body>
<div>
<script type="text/javascript">
function NewPage() {
document.location.href = "http://www.nextservice.pt/"
}
</script>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Btn2" runat="server" Text="OK" onclick="Button2_Click" />
CODE1: <asp:Label ID="Label1" runat="server" Text="Label" ForeColor="#CC0000" />
</form>
</div>
</body>
and I'm working with web forms, and I wont call this button on aspx.cs
public partial class SITE_TESTER : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click (object sender, EventArgs e)
{
string code = TextBox1.Text.ToString();
if (!verifyCode(code)) // comparing users from table
{
Label1.Text = "Not Exists"; //for invalid code
}
else
{
Label1.Text = "Exist"; //for sucsseful code
/*
I Wont call my JavaScript Function here!!!!
*/
}
}
}
you can call a javascript method from server side in asp.net by following ways:
protected void button_Click(object sender , EventArgs e)
{
string jsMethodName= = "NewPage()";
ScriptManager.RegisterClientScriptBlock(this, typeof(string), "uniqueKey", jsMethodName, true);
//or
//ScriptManager.RegisterStartupScript(this, GetType(), "NewPage()", false);
}
you can use either ScriptManager.RegisterStartupScript or ScriptManager.RegisterClientScriptBlock
so difference between the two is explained below:
Let's say we have a .aspx page with the following form tag : (Line
nos. are for reference)
1. <form id="Form1" runat="server">
2. ..
3. ..
4. ..
5. </form>
Now let's look at key differences for each method :
A.
Page.RegisterClientScriptBlock() will insert the block of script
before Line 2.
Page.RegisterStartupScript() will insert the script after Line 4.
B.
Page.RegisterClientScriptBlock() should usually be used for scripts
encapsulated in functions. (hence the word "block")
Page.RegisterStartupScript() can be used for any script, even if it's
not in a function.
C.
Page.RegisterClientScriptBlock() should be used for functions that
don't need to run on Page load.
Page.RegisterStartupScript() should be used for scripts that must run
on Page Load.
D.
Page.RegisterClientScriptBlock() should be used for a script that does
not require the form elements to have been created.
Page.RegisterStartupScript() should be used for scripts that require
the form elements to have been created and uses references to them.
Notice that all the 4 differences are essentially related to each
other (they build upon the prev. one). The difference put in one line
can sometimes be too subtle.
you can know more about these from here and here
You can add a script which will be executed when page is loaded to browser:
Page.RegisterStartupScript("unique_key", "<script type=\"text/javascript\">NewPage()</script>"); // but this is deprecated function
or like this:
ClientScript.RegisterClientScriptBlock(this.GetType(), "unique_key", "NewPage()", true);
But if you simply want to do a redirect (as I can see from your NewPage function), you can do:
Response.Redirect("http://www.example.com");

ASP.Net session not updated in javascript

when my button is clicked I fire the javascript to get the session..
But value of session not updated...
alert('<%= Session["file"]%>');
It won't be up to date if its changed after the page is rendered.
You might want to look at page methods (an ajax system) or another ajax approach.
Any inline code once rendered to the page will not change, which is a normal behavior.
use a Hidden field instead.
mark-up:
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
Session["file"] = "Data Here";
HiddenField1.Value = Session["file"].ToString();
}
javascript:
alert(document.getElementById('<%= HiddenField1.ClientID %>').value);

Categories