How to call function in code-behind in c# with javascript?
I have this code behind :
protected void btn_Click(object sender, EventArgs e)
{
if (btn != null && btn.Checked)
{
Response.Redirect(string.Format("get.aspx?a={0}&b={1}",
a.SelectedValue, b.SelectedValue));
}
}
And I have a Checkbox :
<asp:CheckBox ID="btn" runat="server" Checked="false" />
I am tryong to call that function btn_Click in javascript :
var btn = document.getElementById("btn");
if (btn.checked) {
'<% = btn_Click() %>'
}
But not worked!!! Why?
Thanks.
You can do a proper ajax approach explained here -> http://www.techillumination.in/2013/07/an-aspnet-way-to-call-server-side.html
you can do it like this using Jquery, This is not tested
var button = $("#btn");
$(button).trigger("click");
Related
I need to navigate to the certain tab when button is clicked.
The button is
<asp:Button ID="ButtonFind" runat="server" Text="Buscar" CssClass="btn btn-primary" UseSubmitBehavior="true" OnClick="ButtonSearch_Click" />
JavaScript
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}
// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
})
But somehow the method
protected void ButtonSearch_Click(object sender, EventArgs e)
{
// Fill Grid code
}
is replaced with
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Fill Grid by default
}
}
And finally the grid has no found data and has default data. That's a problem.
I have try to use this
protected void ButtonSearch_Click(object sender, EventArgs e)
{
// Fill Grid code
string url = Request.Url.GetLeftPart(UriPartial.Path) + "#AllWorkOrders";
Response.Redirect(url, true);
}
but there is a
if (!IsPostBack)
{
// Fill Grid by default
}
still ...
I mean I need somehow return user to the correct TAB but Response.Redirect establish some trouble...
Probably there is a way to add #AllWorkOrders part of QueryString to
<asp:Button ID="ButtonFind" runat="server" Text="Buscar" CssClass="btn btn-primary" UseSubmitBehavior="true" OnClick="ButtonSearch_Click" />
but I don't know how to do it.
Any clue?
I found solution that was quite easy to implemenet hahahahaa
I completely forgot about PostBackUrl property!
So the code looks like this now
<asp:Button ID="ButtonFind" runat="server" Text="Buscar" CssClass="btn btn-primary" UseSubmitBehavior="true"
PostBackUrl="~/MyPage.aspx#AllWorkOrders" OnClick="ButtonSearch_Click" />
I have an button in my aspx web page, which should be 'clicked' in my code behind c# code. The OnClientClick method then call a JS confirm dialog box and so the btn_Click function only get executed when user click 'OK'...
This is my code so far:
Variante 1
aspx:
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" />
aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
// set OnClientClick
btnConfirm.OnClientClick = "confirm('Save in DB?');";
// invoke method
Type t = typeof(System.Web.UI.WebControls.Button);
object[] p = new object[1];
p[0] = EventArgs.Empty;
MethodInfo m = t.GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);
m.Invoke(btnConfirm, p);
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
//save something in database
}
Got code samples by: http://forums.asp.net/t/1046550.aspx?How+do+you+raise+a+button+click+event+from+outside+the+button+
I want to call the OnClientClick method, but when I replace 'OnClick' with 'OnClientClick' this error appear:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Edit:
Variante 2:
I tried to rewrite my program like this:
aspx:
<script language="javascript">
function invokeButtonClick() {
document.getElementById("btnConfirm").click();
}
function Validate() {
return confirm('Save in db?');
}
</script>
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" OnClientClick="return Validate();" />
aspx:cs:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "InvokeButton", "invokeButtonClick();", true);
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
// save something in database
}
But then the page postback before my btnConfirm_Click function get called...
Thanks,
Michael
If OnClientClick has a return value of true then the codebehind OnClick event will fire. If OnClientClick is returned false then it won't.
If OnClientClick doesn't return anything the codebehind event will fire regardless. So you want..
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" />
<script language="javascript">
function Validate() {
return confirm('Save in db?');
}
</script>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
// set OnClientClick
btnConfirm.OnClientClick = "return Validate();";
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
//save something in database
}
UPDATE:
This post just came to my attention, don't know why I didn't include it in my original post but you can use 'OnClientClick' in the aspx tag:
<asp:Button runat="server" ID="btnConfirm" OnClientClick="return Validate();" Text="Confirm" OnClick="btnConfirm_Click" />
<script language="javascript">
function Validate() {
return confirm('Save in db?');
}
</script>
You need to Add both the events on the button click. OnClientClick handles the Client side script code and OnClick handles the server side event calling.
So add both events and there handlers. The NullReferenceException you are getting because of that.
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" OnClientClick="return Validate();" />
and in your javascript code can be
function Validate(){
if (valied())
return true;
return false;
}
100% code behind confirmation! Sometiems its so annyoing to Code behind or Server side confirmation in asp.net when you want to Delete or Update something, I got its solution after a long search as below:
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="return confirm('Are you sure to BLOCK this customer ?')" OnClick="btnSave_Click" />
Now whenever you will click this button it 'll ask to confirm, if you 'll select "NO" page will not post and if you select "Yes" then page will post and your button click event will be fire... like below
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
// Before coming here,,,there will be confirmation
protected void btnSave_Click(object sender, EventArgs e)
{
GetCustomerInfo();
}
So the code I have is:
PrintPage.aspx
<asp:Button ID="ViewAuctionsButton" OnClientClick="checkValidated();" Text="Visa" CssClass="" runat="server" />
<script type="text/javascript">
function checkValidated() {
if (document.getElementById('remember').checked)
{
ViewAuctionsButton_Click;
}
else
{
ViewAuctionsButtonChecked_Click;
}
}
</script>
PrintPage.aspx.cs
protected void ViewAuctionsButton_Click(object sender, EventArgs e)
{
*do stuff*
}
protected void ViewAuctionsButtonChecked_Click(object sender, EventArgs e)
{
*do stuff*
}
I hope you are seeing what I am trying to do here. "remember" is a checkbox but that's not really important because I know for a fact that when I click the button it will run the if / else code in checkValidated. (I tried it with alert("") boxes.).
Now I have no idea how to make this run beucase it doesn't seem to react to the "ViewAuctionsButtonChecked_Click;".
But if I instead change the code to following:
<asp:Button ID="ViewAuctionsButton" OnClick="ViewAuctionsButtonChecked_Click;" Text="Visa" CssClass="" runat="server" />
Then it will run. But then I am missing the part about the checkbox being checked or not. Any ideas on how I can fix this?
Thanks in advance.
You should make the "remember" checkbox a server-side control, ie:
<asp:CheckBox ID="RememberCheckBox" ... />
That way you can use OnClick="ViewAuctionsButton_Click;", and get the checkbox's value inside that method:
protected void ViewAuctionsButton_Click(object sender, EventArgs e)
{
if (RememberCheckBox.Checked)
// do stuff
else
// do stuff
}
I want the button "Button_Join" to be enabled when the row "join status" in my table is true and disabled when it's false.
Code:
<asp:Repeater ID="RepeaterTeam" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:Button ID="Button_Join" runat="server" Text="Join" Enabled='<%#Enabled() %>'/>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected bool Enabled()
{
if (Session["join status"] == "False")
{
return false;
}
else
{
return true;
}
}
I dont know how to do it, but that was my guess, but it doesn't seem to work.
Is this possible instead of all this code behind?
<asp:Button ID="Button_Join" runat="server" Text="Join" Enabled='<%#Eval ("join status") %>'/>
Try this with your Enabled function
Enabled='<%#Eval("Enabled")%>'
Why not do it in the button's load event?
protected void Button_Join_Load(object sender, EventArgs e)
{
// your logic...
(sender as Button).Enabled = false;
}
EDIT:
If as per your comment the button is in a repeater, use the repeater's ItemDataBound event:
protected void Your_Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem ri = e.Item;
var btn = (ri.FindControl("Button_Join") as Button);
if (btn != null) btn.Enabled =
bool.Parse((Session["join status"] ?? false).ToString()) == true ? true : false;
}
Set enabled of control in code behind.
protected void Page_Load(object sender, EventArgs e)
{
this.Button_Join.Enabled = Session["join status"] != "False";
}
UPDATE
Add handler of OnItemDataBound for your repeater
<asp:Repeater runat="server" ID="myRepeater" OnItemDataBound="myRepeater_ItemDataBound">
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Button button = (Button)e.Item.FindControl("Button_Join");
button.Enabled = Session["join status"] != "False";
}
And better put in session bool instead string. You will be able use it this way
button.Enabled = (Session["join status"] as bool?) ?? false;
I guess you might have to use Enabled='<%=Enabled() %>' instead of Enabled='<%#Enabled() %>'
<%# %> used for data binding. I see that you are not binding any data.
<%= %> is equivalent of Response.Write()
More info here...
I also made this question before but the problems remains here:
I have this code:
<asp:Button ID="CrearCuenta" UseSubmitBehavior="false" OnClientClick="return validate()" runat="server" Text="Ready" />
The javascript code:
function validate()
{
return false;
}
But in case that it return true, how do i execute de server side onclick function?? Thats what i cannot figure out.
I know that similars question have been posted before, but none answer the question above.
I hope, here is what you need:
<asp:Button ID="CrearCuenta" UseSubmitBehavior="false"
OnClientClick="return validate()" OnClick="CrearCuenta_Click"
runat="server" Text="Ready" />
Javascript:
function validate()
{
if()
return false; //if validation fails
else
return true;
}
Server Side:
protected void CrearCuenta_Click(object sender, EventArgs e)
{
//Put server side processing here
}
Have you added the server side event handler?
In your page code:
<asp:Button ID="CrearCuenta" OnClick="btn_Click"....
In your code-behind:
protected void btn_Click(object sender, EventArgs e)
{
....
}
check this code
document.getElementById('YourFrom').onsubmit = function() {
return false;
}