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)
Related
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.
I'm trying to use the HTML 5 button element to submit an ASP.NET form. I also want it to not trigger validation when clicked. This will submit the form, but will still cause validation to trigger:
<button runat="server"
CausesValidation="false"
type="submit"
name="myButton"
id="myButton">Press Here</button>
I'm specifically trying to not use HTML input or ASP:Button elements. They both will work, but don't allow HTML (images etc..) within the button text.
An example validation element on my page:
<asp:RequiredFieldValidator
ValidationGroup="myValGroup"
ControlToValidate="phone"
ID="phoneRequiredVal"
runat="server"
ErrorMessage="Phone is required."
Display="Dynamic"
CssClass="defaultErrorText"></asp:RequiredFieldValidator>
Any ideas?
Enter the LinkButton control. Looks like this is what I needed to submit the form, have HTML within the tags, and be able to halt validation:
<asp:LinkButton
runat="server"
CausesValidation="false"
CssClass="button fullWidth">Press Here</asp:LinkButton>
Found here:
How do I make a form submit with a LinkButton?
Although you use an HTML tag (<button>) as a server-side control (<button runat="server" ...>), the ASP.NET server does not expect this component as a postback or callback sender. As a result, the Event Validation error occurs on the server side during form submit.
To resolve this issue, register the button as a postback sender using ClientScriptManager.RegisterForEventValidation method:
public partial class _Default : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
Page.ClientScript.RegisterForEventValidation("myButton");
base.Render(writer);
}
}
i want to upload an image on my host in my aspx page.but can i do that with ajax?(i mean,no postback done during the upload).
i look at the gmail file uploader,the classic mode used flax(this is bad idea) but i can understand about the modern mode?!!
according to my search in Google it is impossible for security reasons may be occure
some body help me about this issue."upload a file using ajax"
you can do like this.. using ajax .....
STEP 1: first create an upload form in separate page which is like this (myIframe.html)
<form method="POST" target="_self" enctype="multipart/form-data" action="main.aspx">
<input type="file" name="fileUpload" />
<input type="submit" value="UPLOAD" />
</form>
STEP 2: In main page (main.aspx), you have to put an iframe and loaded that page in it. you can also made borders invisible so it did not look like it is an iframe.
<iframe name="iUploadFrame" src="myIframe.html" frameborder="0" onload="iUploadFrameLoad();"></iframe>
Note that this is specifying onload event handler function of javascript. that one will explain it below.
STEP 3: For testing, in main.aspx and in UpdatePanel with a button and label like this:
<asp:UpdatePanel ID="pnlMain" runat="server">
<ContentTemplate>
<asp:Label id="lblMessage" runat="server" />
<asp:Button id="btnUploadComplted" runat="server" style="visibility:hidden;" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnUploadCompleted" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Note that if you want you can hide the button using CSS style, but not setting visible=”False” attribute. This is because if you want to have the button html in the output document and would want to trigger the ajax callback via that button.
STEP 4: you can define the click event hander of the button in the codebehind like this :
protected void btnUploadCompleted_Click(object s, EventArgs e) {
lblMessage.Text = "UPLOAD PROCESS COMPLETED SUCCESSFULLY";
}
STEP :5 Now, to save file you can do write the code in the code-behind like this:
protected void Page_Load(object s, EventArgs e) {
if ((Request.Files.Count == 1)) {
// process to save file
Response.Write("SUCCESS");
Response.End();
}
}
STEP:6 Now all that we need to do is create javascript function to integrate the process into ajax implementation. The event will trigger when upload process is complete, and it will, in turn, triggers btnUploadCompleted’s click event, which is responsible for making our ajax call.
<script type="text/javascript">
function iUploadFrameLoad() {
if (window.iUploadFrame.document.body.innerHTML == "SUCCESS") {
document.forms[0].elements[btnUploadCompleted].click();
}
}
</script>
I hope it will helps you...
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"];
Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?
For example, this works:
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
and this doesn't (no error):
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
but this works:
<asp:Button runat="server" OnClientClick="alert('Hi');" />
and this doesn't (compile time error):
<asp:Button runat="server" OnClick="alert('hi');" />
(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all.
Because they are two different kinds of controls...
You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
renders to
<input type="check" OnClick="alert(this.checked);" />
and
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
renders to
<input type="check" OnClientClick="alert(this.checked);" />
Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...
When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.
You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx
Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.
For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged
I was cleaning up warnings and messages and see that VS does warn about it:
Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.
Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:
C#:
private void Page_Load(object sender, EventArgs e)
{
SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
}
Note: Ensure you don't set AutoEventWireup="false" in page header.
VB:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
End Sub
You can do the tag like this:
<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />
The .checked property in the called JavaScript will be correct...the current state of the checkbox:
function checkchanged(obj) {
alert(obj.checked)
}
You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});
<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />
protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
using (myDataContext db = new myDataDataContext())
{
CheckBox chk = (CheckBox)sender;
RepeaterItem row = (RepeaterItem) chk.NamingContainer;
var studentID = ((Label) row.FindControl("lblID")).Text;
var z = (from b in db.StudentApplicants
where b.StudentID == studentID
select b).FirstOrDefault();
if(chk != null && chk.Checked != z.FinancialAid){
z.FinancialAid = chk.Checked;
z.ModifiedDate = DateTime.Now;
db.SubmitChanges();
BindGrid();
}
gvData.DataBind();
}
}
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);