handle htmlinputbutton click on the server - asp.net

I have a simple htmlinputbutton of type "submit" in my aspx page.
<input id="Submit1" runat="server" type="submit" value="submit"/>
If I click it I want to handle this as an event on the server. Much like how a normal asp:Button would do.
EDIT: I've tried the onserverclick thingy...it didn't work. Used onserverclick="foo"
In my code behind did something like:
void foo(object s, EventArgs e)
{
}

HtmlInputButton provides a ServerClick which should do what you're looking for.

<input id="Submit1" runat="server" value="submit" onclick="" type="submit" />
In the onclick parameters you can put a custom event handler in java script.
If you want to use a code behind in the C# file I would recommend doing a post back and passing in the post back event arguments, and then have your page load catch those event arguments. You can get event arguments using:
Request["__EVENTARGUEMNT"];

Related

asp OnClientClick not executing

This button:
<asp:Button ID="btnUpload" runat="server" Height="26px" Text="Upload" Width="86px" OnClick="btnUpload_Click" />
With added attribute in Page_Load:
btnUpload.Attributes.Add("OnClientClick", "javascript:alert('Test');")
Shows in browser Inspector:
<input type="submit" name="ctl00$MainContent$btnUpload" value="Upload" id="btnUpload" class="aspNetDisabled" onclientclick="javascript:alert('Test');" style="height:26px;width:86px;">
but never fires onClientClick. Tried calling function, preceding with 'javascript', many things.... but it never executes what's in onClientClick.
Note: The button's regular OnClick="btnUpload_Click" executes fine.
Any ideas?
This just adds a raw attribute to the resulting HTML:
btnUpload.Attributes.Add("OnClientClick", "javascript:alert('Test');")
And there is no OnClientClick in HTML, so the browser has no reason to make any use of it. That's something the ASP.NET server-side controls use and translate into client-side code. Add it directly to the server-side control instead:
<asp:Button
ID="btnUpload"
runat="server"
Height="26px"
Text="Upload"
Width="86px"
OnClick="btnUpload_Click"
OnClientClick="alert('Test');"
/>
Alternatively (and I don't have a way to test this at the moment), if it's a property on the control then you may be able to add it as such:
btnUpload.OnClientClick = "alert('Test');"
As an aside... If OnClientClick is continuing to cause problems then I'd recommend abandoning it altogether. (I honestly don't know why it even exists, other than as a vestige from a time when ASP.NET was trying to take the web out of web development.) If you just want to attach a click handler in JavaScript, you don't need C#'s permission to do that. Just attach a click handler in JavaScript:
const btn = document.querySelector('#btnUpload');
if (btn) {
btn.addEventListener('click', function () {
alert('Test');
});
}
Adding that to a <script> element at the end of the page would add that function as a click handler to the #btnUpload element.

Opening Page In New Tab Updates Both Tabs

I am working with two files, Default.aspx and Beta.aspx.
In Default.aspx I have a button that navigates to a Beta.aspx
<telerik:RadImageButton ID="btn26" runat="server" Skin="Material" Text="26" OnClick="btnConfirm_Click26">
</telerik:RadImageButton>
protected void btnConfirm_Click26(object sender, EventArgs e)
{
string url = string.Format("Beta.aspx?year={0}&track={1}&event={2}&car=26&session{3}", hidYear.Value, hidTrack.Value, hidEvent.Value, hidSession.Value);
Response.Redirect(url);
}
I have the Beta.aspx form tag set up like so in order to force the page to load as a new tab:
<form id="form1" runat="server" class="SmallFont" target="_blank">
The button works, and loads the page in Beta.aspx as a new tab like I had hoped for, however the Default.aspx page that the button resides on also navigates to the same URL. I want Default.aspx to always stay on the same page, what am I missing here?
To open a new tab, there is no need to do a server round-trip. You need to move your button onto a separate html form, skip the aspx code and handle the click event using (client-side) JavaScript, like this:
<form id="form2" class="SmallFont" action="Beta.aspx" target="_blank">
<input type="submit" ID="btn26" Skin="Material" Text="26" />
<input type="hidden" name="year" value="{0}" />
<input type="hidden" name="track" value="{1}" />
</form>
or this: (which might not work as-well because of popup blockers)
<input type="button" ID="btn26" Skin="Material" Text="26"
OnClick="window.open('Beta.aspx?year={0}&track={1}&event={2}&car=26&session{3}', '_blank');" />
If you don't like the old-school JavaScript, there are more-modern ways, with jQuery or other frameworks, etc. HTML button onclick event
This should be a pretty easy problem, let's put few more details out here.
There is a form on default.aspx
<form id="form1" runat="server" target="_blank">
<asp:Button ID="btn26" runat="server" OnClick="btnConfirm_Click26" Text="26" />
</form>
The target is _blank, i.e. the new window, or tab will be opened.
The code of btnConfirm_Click26() of default.aspx has redirect
protected void btnConfirm_Click26(object sender, EventArgs e)
{
string url = string.Format("Beta.aspx?year={0}&track={1}&event={2}&car=26&session{3}", 0, 1, 2, 3);
Response.Redirect(url);
}
i.e. the form of default.aspx in first tab will be submitted to a new window to the same default.aspx and then redirected (in same second tab) to beta.aspx.
default.aspx (in first tab)
--> default.aspx (in new tab) --> redirects to beta.aspx
If you have no code in Page_Load() of default.aspx, it should "stay" as-is in the first tab and will not "navigate to beta.aspx". If you have code in Page_Load(), make sure you use if (!Page.IsPostBack) to execute code only once when default.aspx is loaded (and not when it is redirected to beta.aspx).
As mentioned earlier, redirect does not require to be executed on server and can be done via client script too.

Difference between button and asp:button onclick

I am new to developing in asp.net for making web sites.
What is the difference between an asp:Button and an input button?
Code 1
aspx code
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Codebehind
protected void Button1_Click(object sender, EventArgs e)
{
//Do somthing
}
Code 2
aspx code
<input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" />
<script language="javascript" type="text/javascript">
// <![CDATA[
function Submit1_onclick() {
//Do somthing
}
// ]]>
</script>
The first code it is a server side code. When you add a tag asp:button in your webform, the asp.net will render an input type="button" for you and when you click this button, it will submit a post to the same page (this is called postback) and will processing the life cycle and asp.net event associated with this button. The same is valid for every server control such as TextBoxes (render input type='text'), Panels (renders divs), Checkboxes (render input type='checkbox'), Labels (render spans) etc...
In the second code, you have the code that first one will render (an input type = 'button'), but associated with an event in the client-side javascript.
You can also associate a client-side event in a tag asp:button, take a look at the OnClientClick property.
asp:Button is an asp.net server control which fire an event on the server side.
<input id="Submit1" type="submit"
is a client side button of type submit,
but it can act as a server side button as well by adding
runat="server" and onserverclick="eventname"
The first is a server side control and the event handler is executed on the server in C#. Clicking the button will cause a postback and all information in the form will be posted to the server for processing, including a call to the click event handler.
The second is fully client side and the event handler is executed in the browser in JavaScript.
to my understanding you have to keep in mind that there is a cliend side code that will execute, for example javascript in your browser, and asp/c# code that will execute on the server.
So having this control:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Button1_Click will execute on the server, in microsoft world it is IIS, on the other hand
you have just a pure html control, where you hook up a javascript function for the click event
<input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" />
So the server side has nothing to do with this part, this code will execute on your machine, in your browser.
A mí me funcionó así:
1.- En el botón:
<input type="submit" id="btnAccept" value="Log In" runat="server" onserverclick="btnAccept_Click">
2.- En el codebehind:
Protected Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

ASP.NET : Reading form variable values in the action page of search form

I have a website where i want to implement search functionality.So i added the below code to have a search box in my html page
<form id="search" method="post" action="Results.aspx">
<input id="txtSearchKey" type="text" name="txtSearchKey" />
<input id="Submit1" type="submit" value="submit" /><br />
<br />
</form>
In Results.aspx, I want to read the value user has entered in the txtSearchKey text box. What is the ideal way to do this ? I used
string strKey = Request.Form["txtSearchKey"].ToString();
But it throw a null reference exception.
I don't want to have all pages in ASP.NET.I want to have only the result page as ASP.NET
Could be because you do not have a NAME attribute on the textbox field. That's the value that is used as the key in the Request.Form collection. An input field without a name attribute will not be submitted, I think.
e.g.:
<input id="txtSearchKey" type="text" name="txtSearchKey" />
You can get your txtSearchKey field by this :
string strKey = PreviousPage.Request.Form["txtSearchKey"].ToString();
But, instead of using form action to forward your search to another page, you can use a button with PostBackUrl property like that :
<asp:Button runat="server" ID="btnSearch" PostBackUrl="Search.aspx" />
Because in ASP.NET, to have more then one form is not allowed.
Is there any reason you don't use
form runat="server"
and then drag a TextField and a Button in this form. Then doubleclick the button and write code you want.
If you want to do it your way you need to give your s a name="txtMySearchKey" for it to work
The way you are going about things is not really the way you work in ASP.NET web forms. The preferred way is to use asp.net server controls and events to abstract the process you are trying to achieve. For instance, your form should really be something like this (note the runat="server" attribute that enables you to reference the controls programmatically):
<form id="form1" runat="server">
<div>
<asp:Panel ID="PanelSearch" runat="server" DefaultButton="ButtonSubmit">
<asp:TextBox ID="TxtSearchKey" runat="server" /><br />
<asp:Button ID="ButtonSubmit" Text="Submit" runat="server"
onclick="ButtonSubmit_Click" /><br />
</asp:Panel>
</div>
</form>
Then, in your code behind you would handle the ButtonSubmit_Click event like this to enable you to get the value from the TxtSearchKey textbox:
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
string strKey = TxtSearchKey.Text;
}
See the Quickstart example for the TextBox control for more info.
Just do not use .toString() after the Request.form... it will not give a null reference after that.

How to set html button as default for ASP.Net form?

Well, I'm trying to make ASP.NET urls looking user-friendly, like it was explained in this question. So I created an ASP.Net form, and placed asp:textbox and asp:button on it. Also I set onclientclick attribute to call JS function which navigates to smart URL by setting windows.location.href. In Firefox it works well but in IE and Opera the browser first navigates to smart url but then it closes connection and sends a postback using an asp.net form action.
I tried to solve it using html button instead of server ones. It works, but the problem is that it can't be set as default for the asp.net form. So' if user clicks on it, it does its work. But if the user just presses enter when form is active, the form performs its action, so the button is not pressed and JS url rewriting doesn't occur. So how can I solve this problem?
My JS looks like this:
function searchRedirect() {
var query = $get('colSearch');
window.location.href = 'colSearch?q=' + query.value;
return false;
}
and in search.aspx i have
<form id="MainForm" runat="server" method="get">
<asp:TextBox id="colSearch" runat="server" Width="615px" CssClass="searchLine"></asp:TextBox>
<input id="Button1" type="button" value="Search!" onclick="searchRedirect();" class="search" />
I also tried with asp:button:
<form id="MainForm" runat="server" method="get" defaultbutton="submitReqBtn">
<asp:TextBox id="colSearch" runat="server" Width="615px" CssClass="searchLine"></asp:TextBox>
<asp:Button runat="server" Text="Search!" ID="submirReqBtn"
onclientclick="searchRedirect();" CausesValidation="False"
EnableViewState="False" UseSubmitBehavior="False"></asp:Button>
</form>
Your onclientclick event needs to return false;
The form accepts an attribute showing which of the buttons are set as default: use it as in
<form id="form1" runat="server" defaultbutton="Button1">
where Button1 is the id of a button on the page.

Resources