C# code behind for Button Click Event, ASP.NET - c#

I'm working with HTML provided by coworker in .aspx and I need to program in .aspx.cs(C#) the functionality of the button he created using HTML.
The code I'm dealing with is as follows:
<div>
<button style="padding: 10px; margin-bottom: 10px;" class="w3-round w3-blue">Ship</button>
<button style="padding: 10px; margin-bottom: 10px;" class="w3-round w3-blue">Rate</button>
</div>
I'm new to HTML but in looking at solutions to similar questions I often see the HTML code for a functional button looking more like
<button type="submit" runat="server" id="btnLogin" class="button" onclick="btnLogin_Click();">
and sometimes with an
<asp:
at the beginning. I've tried simply adding the runat and onclick fields to the HTML that correspond with a C# method in the aspx.cs code behind but I haven't been able to make the button click actually trigger the method in the code behind. I've assumed that if I add the method with the name that follows onclick to the C# aspx.cs code then it would simply execute this upon the clicking of the button but I'm clearly mistaken.
Can I program the button's functionality in the code behind without changing the HTML provided to me? Or must I alter the HTML first and if so how?

You could probably get away with adding the runat="server" attribute to your buttons but I've never tried it and frankly, using proper web controls would be the best way to go.
Replacing them shouldn't change the look and feel of the page at all. Just add CssClass="xxx" to apply the css if there is any, otherwise they render to standard html elements anyway.
Your markup should look something like this:
<asp:Button runat="server" id="btnLogin" Text="Log In" OnClick="btnLogin_Click" />
The matching event handler in your code would look like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
// Here's where you do stuff.
}

you need to replace the
onclick="btnLogin_Click();"
with
onclick="btnLogin_Click"
because the onClick property of asp.net buttons need to contain the name of the function it calls in the aspx.cs file and not the actual call.

<button type="submit" runat="server" id="btnLogin" onserverClick="btnLogin_Click1">login </button>
just replace the onClick with onserverClick

My suggestion would be to change the HTML control to <asp:Button /> and have the event handler wired up by ASP.NET. Syntax would look something like below
<asp:Button ID="Test" runat="server" Text="Button" OnClick="Test_Click" />

There are ways to reach asp.net code behind handler from html controls. You could try adding onserverclick handler or you could do a postback with arguments and add handler to the postback in contructor.
Few links to help you with it:
https://forums.asp.net/t/1650304.aspx?Calling+code+behind+function+from+a+html+button
calling server side event from html button control

If you are using a tool like Visual Studio/Express bring up the page in question (the aspx page).
From the controls toolbar drag a button over to the page.
If you double click the button in design view it will automatically create the event handler in code behind.
The button control has a couple of properties OnClick and OnClientClick. Use OnClientClick to trigger any JavaScript on the page.
Hope it helps

Related

How can I hide this button in ASP.NET getting value from Method?

I have a button in HTML like this:
<button id="EditTemplate" value="<%=this.GetUrlEncode() %>" class="btn-primary" type="button">
<em class="fa fa-edit"></em>Edit template
Because I'm using the Value="<%=this.GetUrlEncode() %>", It can't have runat="server" as property because the button will not work. The problem is that I need to hide and show the button in c#:
this.EditTemplate.Visible = false/true;
It doesn't work because it needs to be runat="server". Any ideas?
I just found the solution by adding an attribute called value in the C# code like this
EditTemplate.Attributes.Add("value", this.GetUrlEncode());
so this let me to set runat="server" and still works

Asp .Net Web Forms removing postback from asp:linkbutton with inner HTML tags

I have created my first fully functional listview with custom action buttons, that worked fine when I used asp:buttons, but I need the buttons to be icons, so I tried inserting HTML tags inside, since it can't be done out of the box, I used as:linkbuttons controls to achieve the desired look.
What it does is that the buttons trigger several actions that populate controls inside update panels, and I have my own Javascript that shows a popup on click, but on the second action it currently sends a postback and page is reloaded, I googled other questions and tried everything they had, what I tried:
Adding a return false on client click
<asp:LinkButton runat="server" OnClientClick="showDialog('#popup'); return false;" CommandName="Detalles" CssClass="toolbar-button" ID="EditButton">
Editar
<span class="mif-pencil"></span>
</asp:LinkButton>
Using an HTML button with runat server, but Command doesn't trigger
<button runat="server" onclick="showDialog('#popup');" CommandName="Detalles" class="toolbar-button" ID="EditButton">
Editar
<span class="mif-pencil"></span>
</button>
And on jQuery, but doesn't do any difference
$('.toolbar-button').removeAttr('href');
What exactly I'm missing, my code works fine with Asp:buttons, but they can't have additional HTML :(, I'm a newbie on ASP, any hints are appreciated.
Working button that doesn't allow inside HTML
<asp:Button runat="server" Text="Detalles" CssClass="toolbar-button fg-darkCyan button-popup" ID="btn_detalles" CommandName="Detalles">
</asp:Button>
NOTE Buttons are inside a ListView control, and assigned for each item.

How I can use HTML and CSS Tags with a C# Event?

net application and I want to create me a own Button with css and html and use the onclick event for execute c# code. But I get the error:
Runtimeerror in Microsoft JScript: "BtnAdd_Click" is undefine
Here is my Code:
ASPX file:
<div id="GuestListViewControls">
<table>
<td>Hinzufügen</td>
</table>
</div>
My C#:
protected void BtnAdd_Click(object sender, EventArgs e)
{
Response.Write("Add");
}
Can I use this Button with C# Code in a ASP.NET Application? :/
It's not a c# error, It's like a javascript error , Now You can use LinkButton for onclick event, It's look like also anchor tag
<asp:LinkButton ID="MyLink" runat="server" class="GuestButtons" OnClick="BtnAdd_Click" Text="Click Here"></asp:LinkButton>
or use onserverclick event instead of onclick event
test
You are using "A" tag. This is HTML Anchor control and it does not support server side event.
Use
<asp:Button id="mybutton" Text="Submit" runat="server" onclick="BtnAdd_Click" />
You can do it using HTML controls only
you just need to use on onserverclick
Sample Test stuff
test
code behind
protected void anchorclick(object sender, EventArgs e)
{
// do stuff here
}
See Refrence
HTML Anchor Server Side Click
HTML Button Click Server Side
You're getting this error:
Runtimeerror in Microsoft JScript: "BtnAdd_Click" is undefined
Because you're using an onclick event on an HTML anchor tag.
You need to use an asp:Button tag instead, for which the onclick event will point to a server-side method. Something like this:
<asp:Button class="GuestButtons" runat="server" onclick="BtnAdd_Click" text="Hinzufügen"></asp:Button>
You are getting "Runtimeerror in Microsoft JScript: "BtnAdd_Click" is undefine" because onclick searches for the method in the Javascript.
One option would be have a javascript method on the href click and from that method you can invoke the server side method using Ajax post or get or simple .Ajax
Please refer solution 4 in the url http://www.codeproject.com/Questions/334635/how-to-call-a-csharp-function-in-a-href-onclick-ev

OnClick Event not firing when I am specifying action url in asp.net

I need to redirect the user to paypal account. But before that I want to collect name and email for that user. So I am using the following code.
<form id="paypalForm" method="post" action="https://www.paypal.com/cgi-bin/webscr"
target="_top" runat="server">
<div>
<label>
Full Name:<span>*</span></label>
<asp:TextBox ID="name" runat="server" CssClass="large form-poshytip" title="Enter your Full Name."></asp:TextBox>
<label>
E-Mail:<span>*</span></label>
<asp:TextBox ID="email" runat="server" CssClass="large form-poshytip" title="Enter Email Address."></asp:TextBox>
<input type="hidden" name="cmd" value="_s-xclick" />
<div id="partnerFormButton">
<br />
<asp:ImageButton runat="server" Name="btnSubmit" Text=" Next "
ID="btnSubmit"
ImageUrl="https://www.paypalobjects.com/en_GB/i/btn/btn_buynowCC_LG.gif"
onclick="btnSubmit_Click" CausesValidation="False" ></asp:ImageButton>
</div>
</div>
</form>
Code Behind code:
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
//some code
}
But the problem is that OnClick event doesn't firing and it redirects to the specified action url.
What can be the problem?
Thank you so much in advance...!!
It's not how ASP.NET events work. Events are fired after postback is made and you are preventing the postback by submitting the form. You need to decide what to do - either submit data with the form (like what you are doing now) and not use OnClick event or use the event and remove action and method parameters from form.
http://msdn.microsoft.com/en-us/library/ms178472.aspx
To explain it further: an event will not fire right after you click the button. What happens is that a POST request is being made to the same page with the page state passed in the ViewState. In other words - pressing the button in ASP.NET by default works kind of like a link to the same page (it's a veeeery simplified explanation though). Events are fired only after that request is made and after the page is loaded again - see the link above.
What you are doing right now is forcing the request to go to another page. Even though the button 'wants' to do a postback, the action parameter in your <form> points the request somewhere else. Since the postback isn't made and your page isn't loaded again, the event will not fire.
IISTe Technologies is going to introduce a blog for their student and other developers where they can find and share their problem and solution regarding c, c++, .NET java, PHP and others, here you one can find the exact solution of their programming problems.
Basically you have specified the action in the form tag.
You can redirect the page to "https://www.paypal.com/cgi-bin/webscr" in the click event. For if u specif action then you you wont be able to sumbit the data of the for. You won't get the values.
It will never go to the click event code block you have written. Because you are posting the page to paypal page instead of self.
Try this:
Remove action attribute from form.
Write click event as
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
var target = #"https://www.paypal.com/cgi-bin/webscr";
Response.Status = "307 Temporary Redirect";
Response.AddHeader("Location", target);
}

Method being triggered on page load but not via asp button

I have two asp:Labels, the first of which is replaced with a few buttons and the second with a list of items.
I want to click on the buttons to filter the items.
The contents of the buttons are added programmatically by replacing the text with html and works fine.
asp:
<form id="form1" runat="server">
<asp:Label id="filters" runat="server" Text="Filters here"/>
<asp:Label id="itemList" runat="server" Text="List of items here"/>
</form>
resultant html of filters label:
<input type="submit" onclientclick="Load_Items(0)" runat="server" value="First"/>
<input type="submit" onclientclick="Load_Items(1)" runat="server" value="Second"/>
<input type="submit" onclientclick="Load_Items(2)" runat="server" value="Third"/>
relevant c#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Load_Items(0);
}
}
public void Load_Items(int filterType)
{
//code to load items (pseudo below)
for each row in list
if filterType = itemType
build string
replace second label with string
}
On page load everything happens just as I want it to with the contents being filtered by the first item (hence Load_Items(0)), and if I manually change the 0 to another number in Page_Load, it filters by the other types, but if I click the buttons which are programmatically added, nothing happens other than what looks like the page refreshing.
I know the post back check is working by adding a text replacement before and inside it.
I've also added an asp:button to make sure it's not something to do with the way the buttons are added as below (with some extra things recommended from searches):
<asp:Button runat="server" CausesValidation="False" onclientclick="Load_Items(2); return false;" text="Submit" />
So what could be the issue?
The OnClientClick property specifies the javascript to run in the browser when the button is clicked. Since you probably don't have a javascript function called Load_Items, this will generate a script error, and the button will then cause the form to post back.
The server-side Click event will fire on the server, but doesn't allow you to pass a parameter. You will only get the button instance and an empty EventArgs instance.
You might be better off using the Command event, combined with the CommandArgument property.
<asp:Button runat="server" CommandArgument="2" OnCommand="Load_Items" ...
The event handler would use the CommandArgument property of the CommandEventArgs to access the argument from the clicked button:
protected void Load_Items(object sender, CommandEventArgs e)
{
Load_Items(Convert.ToInt32(e.CommandArgument));
}
Well, that's the common problem which I think every asp.net developer deals some time. The common part of it, that asp.net event system doesn't work, as windows forms.
Page object, and all controls on that page, have lifecycle events, that are triggered during any request, even when it's from update panel.
As you create those controls by code, you have to keep in mind, that all events for those controls should work as part of Page object. That's why you have to create those object in Page_Init event, before all other control's event would be triggered.
Please also keep in mind that you have to create those controls as asp.net objects:
var btn = new Button();
But not by simply adding html markup. And you have to recreate them on each request, following that one, when they were created.
Please take a look on my another answer.

Categories