adding handler to button code behind - c#

I am rendering some html in code behind using StringBuilder which includes a button. I am also trying to add a handler to this and I think perhaps not surprisingly it does not fire. Can I include an event handler to a button in this way?
sb.Append("<td>");
sb.Append("<input type='button' runat='server' id='butResetPassword' value='Reset Password' onserverclick='butSendEmail_Click' />");
sb.Append("</td>");
User.InnerHtml = sb.ToString();
this is the eventhandler that appears in the same code behind page
protected void butSendEmail_Click(object sender, EventArgs e)
{
labTester.InnerText = "Thanks for clicking me";
}

I answered a similar question of yours recently.
Unless you have a really good reason to generate markup in the code behind, keep it separate, otherwise stick to classic ASP.
You can do:
Markup:
<asp:Button runat="server" id="butResetPassword" OnClick="butSendEmail_Click" />
Code behind:
protected void butSendEmail_Click(object sender, EventArgs e)
{
//Reset the password here
labTester.InnerText = "Thanks for clicking me";
}
Edit* If all you need to do is display that confirmation message and not interact with any data or controls, then you could bind the button to a js function, change onserverclick to onclick:
<input type='button' runat='server' id='butResetPassword' value='Reset Password' onclick='butSendEmail_Click' />
And then have some js to handle this:
<script type="text/javascript">
function butSendEmail_Click() {
alert("Thanks for clicking me");
//Or set the labels text
var elem = document.getElementById("labTester");
elem.InnerHtml = "Thanks for clicking me";
}
</script>

Related

Adding html button to a list through innerhtml property

I have an html list to which I am trying to add html button to the property "innerhtml" using the code behind file. I am able to add the button however the onclick event is not getting fired
HTML:
<ul runat="server" id="list">
<li></li>
<li><a id="loginID" runat="server" href="../Accounts/login.aspx">Login</a></li>
<li id="logout" runat="server"> Register</li>
</ul>
code behind:
logout.InnerHtml = "<input type=\"submit\" id=\"b1\" runat=\"server\" onserverclick=\"b1_click\" />"; //logout is the id of the list item
}
}
public void b1_click(Object sender,EventArgs e)
{
Response.Redirect("~/Accounts/login.aspx");
}
}
This isn't the right way to dynamically create server-side controls.
Please review the example below to get a better understanding of how to do so. Keep in mind you can not assign the ClientID property as it is read only and initialized during runtime.
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Dynamic Button";
btn.ID = "b1"; // Server Side ID
btn.Click += b1_click;
logout.Controls.Add(btn);
}
public void b1_click(Object sender,EventArgs e)
{
Response.Redirect("~/Accounts/login.aspx");
}

Avoid page refresh click on Button Asp.net c#

enter code here NET application, I have inserted a button that call a Javascript function (OnClick event) and a asp.net function (OnClick event)
The problem is that when I click the button, it refreshes the page.
How can I avoid the page refreshes click on asp button using javascript?
document.getElementById('pageurl').innerHTML = "tryfblike.aspx";
$('#<%= btnsave.ClientID %>').click();
$('#auth-loggedout').hide();
<asp:Button runat="server" ID="btnsave" OnClick="btnsave_Click();" Visible="true" style="display: none;" />
protected void btnsave_Click(object sender, EventArgs e)
{
objda.agentid = "2";
string currenttime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
objda.datetime = currenttime;
ds = objda.tbl_log();
}
First to call JavaScript function, use OnClientClick.
To avoid page refresh, after your function call add return false;
For example:
<asp:Button ID="btnSubmit" runat="Server" OnClientClick="btnsave_Click(); return false;" />
in java script you can use return false.
if you want prevent whole page referesh use ajax.
FirstYou can call javascrip onclick and then simply add
return false;

Can't handle events in ASP.net

I am new to ASP.net. I downloaded one responsive page template from this link. For my convenience I changed this HTML code to asp.net web form(i.e .html to .aspx) I added a button in that page and I generated click event. When I place a breakpoint in the .cs code and when I click this button in the browser the event is not handled. Even I tried with link button and other controls. I wrote some code in page_load event. It works perfectly. How to solve this issue. Any problem with the downloaded template or can't I handle events in such type of layout. Please go through the below code
Even I tried placing outside the html list control. Its not working. Please go through the link for the details of template here
Issue Placed Menu but event is not working. I tried using other control and its working..
<asp:Menu ID="mini" OnMenuItemClick="mini_MenuItemClick" runat="server" Orientation="Horizontal">
<Items> <asp:MenuItem Text="Item">
<asp:MenuItem Text="sdaad" Value="1">
<asp:MenuItem Text="MenuSub1" Value="MenuSub1" ></asp:MenuItem>
<asp:MenuItem Text="MenuSub2" Value="MenuSub2" ></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Item" Value="Item">
<asp:MenuItem Text="MenuSub" Value="MenuSub"></asp:MenuItem>
</asp:MenuItem>
</asp:MenuItem></Items>
</asp:Menu>
I have tried again after download that template and get issue if because of jQuery Validation script, there are three text boxes in bottom so when we are click on our asp.net button then page will first run client side script and client side script will return false so it will not do post-back till validation js will not return true, so to solve asp.net click problem just remove :
<script type="text/javascript" src="js/jqBootstrapValidation.js"></script>
Have you attached ID to your button? Give ID to your Button and try again. As it is server control, it is not so logical to use it without ID... And post your code behind, I need to look at it and then may be I could help you.
One way to check whether the event has been bound to the control, is to go to the design view of the page, select properties for the button, see the section for events and check whether an event has been attached to click. If not double click in the click event section and an event will get attached to your element.
Button.Click event
Why do you want to put that button inside a list control?
Give an ID to your button control.
ID="Button1"
Your Click event should be like this:
protected void Button1_Click(object sender, EventArgs e){
//some code
}
Find and change Categories block to the next:
<div class="categories">
<asp:Button ID="Button1" CssClass="btn btn-primary" runat="server" Text="Button" OnClick="Button1_Click" />
<ul class="cat">
<li>
<ol class="type">
<li>All</li>
<li>Web Design</li>
<li>App Development</li>
<li>Branding</li>
</ol>
</li>
</ul>
<div class="clearfix"></div>
</div>
your ButtonClickListenes is:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<script language='javascript'>alert('Button is working');</script>");
}
Your code behind (full version):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
MyFunction();
}
protected void MyFunction()
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-CEUQVES;Initial Catalog=register;Integrated Security=True;Pooling=False");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Admintr where projectid=mba ", con);
DataSet ds = new DataSet();
sda.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
//GridView1.Columns[0].Visible = false;
}
}
protected void Unnamed_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "view")
{
string str = e.CommandArgument.ToString();
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + str + "\"");
Response.TransmitFile(Server.MapPath(str));
Response.End();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<script language='javascript'>alert('Button is working');</script>");
}

No response when call button click in javascript

Good day,
I have a aspx contain a button with ID button1, the following is my aspx code :
<div>
<asp:LinkButton ID="lnkView" CommandName="VIEW" runat="server">View</asp:LinkButton>
<asp:Button ID="button1" runat="server" Text="OK" onclick="button1_Click" />
</div>
/*
some code here
*/
<script>
function test()
{
document.getElementById("<%=button1.ClientID %>").click();
alert("hello");
return true;
}
</script>
The following is my aspx code behind:
//some code here
lnkView.Attributes.Add("onclick", "return test()");
//some code here
protected void button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Javascript", "<script>alert('Record Added Successfully')</script>", false);
}
As you can see, my linkView link button have a javascript function test() when click on it.
I can alert the "Record Added Successfully" by click on the Button1.
However, when I click on linkView link button, the "Record Added Successfully" didnt alert, it only alert "Hello".
I think I am missunderstand in some programming concept.
Kindly advise.
Thanks.
This will trigger the event in code behind.
Try this in your .aspx page:
//Code:
<script type="text/javascript">
function test(parameter)
{
__doPostBack('button1_Click', parameter)
}
</script>
You can fix this by returning false instead of true as the result of the function test(). This way you will cancel default behavior of the link with ID lnkView ie sending form

A pragmatical point of view to ASP.NET's page cycle

I have a form like the following:
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plcHolder" runat="server">
</asp:PlaceHolder>
<asp:Button ID="btnSubmit" Text="submit" runat="server"
onclick="btnSubmit_Click" />
</div>
</form>
And here is my code:
protected string FetchDataFromDatabase()
{
return "some long string";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.plcHolder.Controls.Add(new Label() { Text = FetchDataFromDatabase() } );
}
}
Page_Load() gets a long string from the database.
protected void btnSubmit_Click(object sender, EventArgs e)
{
this.plcHolder.Controls.Add(new Label() { Text = "new text" });
}
My Button adds new text to my page. However, when I click the button, I only see the string "new text" but I was looking for both texts ("some long string new text") instead.
I don't want to call my database at every button click since the text already loaded to the page. How do I achieve this?
I know that this example seems a little weird, it's because I tried to give the minimal working example.
In the load, when you get the value from the database, store it in Session:
Session["textFromDatabase"] = GetTextFromDatabase();
and then leverage that value in both places. So if you were in the click you would say:
... Text = Session["textFromDatabase"] + " new text";
and now you can get the value from the database when it's not a post back, just once like you stated, but leverage it over and over.
And I'm pretty sure, based on what you said, this is the inverse of the condition you want, throw a ! in front of it:
if (Page.IsPostBack)

Categories

Resources