Cannot get onserverclick to work - asp.net

Here's what is in my .aspx:
<div><input id="testButton" type="image" src="<%=TestImageUrl %>" onserverclick="RedirectTest" /></div>
And in my code-behind this:
protected void RedirectTest(object sender, EventArgs e)
{
// Logic is here
}
It's not hitting my method at all when I click the image. And please note, I do not want to use an ImageButton. I want to figure out how to get this working with a plain old input tag.

Seems like you're missing the runat="server" attribute on the input tag.

You need to add runat='server' to the input's definition

you need to add a runat="server" attribute to your input tag.

Related

Asp.net checkbox and html data attribute

In asp.net, if you use a custom attribute, usually it is rendered as-is.
Considering this markup (note: attributes such as id, name and for were removed in all examples as their generated id/names are verbose):
<asp:TextBox runat="server" data-foo="bar" />
Is rendered in asp.net as:
<input type="text" data-foo="bar" />
That is, asp.net keeps data-foo untouched.
Check box are usually rendered like this:
<asp:CheckBox runat="server" Text="Normal" />
Renders as:
<input type="checkbox" />
<label>Normal</label>
But if you add a custom attribute on a checkbox:
<asp:CheckBox runat="server" Text="Custom attribute" data-foo="bar" />
It renders as:
<span data-foo="bar">
<input type="checkbox" />
<label>Custom attribute</label>
</span>
As you can see, a span in rendered to hold the attribute. This also happens if you add the attribute in code behind. This does not happen with any other HtmlControl, AFAIK.
Does anyone know why this span is rendered to hold the attribute?
Is there anyway to render the attribute in the input tag?
I'm not sure why it's rendered with a span, but I suppose you can add the attribute directly to the input element of the CheckBox in code-behid like this:
myCheckBox.InputAttributes.Add(...)
Reference links:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.inputattributes.aspx
http://forums.asp.net/p/541142/541562.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.attributecollection.add.aspx
Update
An additional parent element is used, so that the attributes you apply to a CheckBox can affect both the input and the text. I suppose it's a span (and not a div), because it's an inline element, making it more convenient to use in different scenarios.
Reference links:
http://en.wikipedia.org/wiki/Span_and_div#Differences_and_default_behavior
http://learnwebdesignonline.com/span-div
This is the way that render engine builds the CheckBox control, there isn't very much to do about it.
Something you could do is creating a runat="server" input.
<input id="myInput" runat="server" type="checkbox" data-foo="bar"/>
<label>Custom attribute</label>
Another option is adding the data-foo attribute using jquery on document load
$(function(){
$('span[data-foo]').each(function(){
var $span = $(this);
var value = $span.data('foo');
$span.find('input').data('foo',value);
});
})
Just to add another method that I use when all else fails, you can always use a literal control and make it render whatever you want. You need to do a bit more work when handling the postback, but sometimes this is the only way to get the html you need.
Markup:
<asp:Literal ID="myLiteral" runat="server"/>
Codebeside:
myLiteral.Text = string.Format("<input type=\"checkbox\" data-foo=\"{0}\" /><label>Normal</label>", value)
If you are trying to access that attribute on click event you can do that by casting the control. For example I have a check box and I assign it a custom attribute like you did
<asp:CheckBox runat="server" data-foo="bar" />
Now on OnCheckedChanged I need to get that value and in my method I got a sender object.
protected void chk1_CheckedChanged(object sender, EventArgs e)
{
CheckBox myControl = (CheckBox)sender;
string value = myControl.Attributes["data-foo"].ToString();
}
I hope this help someone

HTML forms in ASP.NET

Hello all how to use HTML text field instead of ASP.NET textbox.?
How to write C# code to make use of HTML forms instead of ASP.NET
EDIT:
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Text1" type="text" runat="server" />
<asp:Button ID="Button5"
runat="server" Text="Button" OnClick="button5_click" />
<div>
<script runat="server">
protected void button5_click(object sender, EventArgs e)
{
Text1.Value = "Hello";
}
</script>
</form>
Instead of using or whatever server control, just type in the standard type tags or whichever HTML control you want.
If you want to be able to access them from your code-behind, then just include a runat="server" value with each HTML tag and make sure you give it an ID.
You need to retrieve the value from the HTTP request's Form collection:
<input type="text" name="MyTextField" />
Code behind:
string value = Request.Form["MyTextField"];
This question doesn't make much sense. You really should clarify and flesh out the question and explain what you are trying to do.
In some ways, an ASP.NET textbox is an HTML text field that C# code can make use of. So what's the problem with an ASP.NET textbox?
You can create an instance of a HtmlInput control in code, or alternatively add a runat="server" attribute to an <input> element in your aspx file, you can then access this from server-side code using it's ID.
As an alternative, you may wish to take a look at http://asp.net/mvc to get better control of your HTML markup.

Setting value in html control in code behind without making server control

Setting value in html control in code behind without making server control
<input type="text" name="txt" />
<!--Please note I don't want put 'runat="server"' here to get the control in code behind-->
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//If I want to initlize some value in input, how can I set here
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Request["txt"] // Here I am getting the value of input
}
This answer comes from memory, so I apologize if it's slightly off.
What you can do is use an ASP.NET inline expression to set the value during the loading of the page.
First, add a property in the code-behind of your page.
protected string InputValue { get; set; }
In the Page_Load event, set the value of the property.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.InputValue = "something";
}
}
Finally, add an inline expression in your page markup like this:
<input type="text" name="txt" value="<%= this.InputValue %>" />
This will let you set the value of the input element without making it a server-side tag.
Elements that are not set runat="server" are considered plain text and collected into as few Literal objects as possible (one between each serverside control). I suppose if you really really wanted to, you could try to find the correct Literal (or maybe LiteralControl) object in Page.Controls, and modify it, but I'd definately recommend against it.
What's so terrible about setting it runat="server" ?
And yes, of course you can also use <%= %>. Embedded code blocks. They're evaluated at Render time, so it should be relatively safe to do so.
Add an expression in your page like this:
<input class="field" id="locality" name="loc" value="<%= this.inputtypeCT %>"/>
Add a property in the code-behind of your page:
protected string inputtypeCT;
In the Page_Load event, set the value of the property:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.inputtypeCT = "test"
}
}
<input type="text" name="txt" value="<%= System.Web.HttpUtility.HtmlEncode(this.InputValue) %>" />
Add runat server
or use Asp controls like below
<asp:TextBox type="text" runat="server" class="demoHeaders" id="datepicker" ClientIDMode="Static" Text=""/>
Also make sure that you used ClientIDMode="Static" for the naming of control to be in clinet as like server.
Enjoy!

ImageButton not hitting codebind method, but does if replaced with LinkButton

I have an ImageButton being build inside of radgridview columnn. It is defined as follows.
<asp:ImageButton ID="ImageButton_DeleteRun" ImageUrl="~/Assets/Images/Misc/delete.png"
runat="server" OnClick="QueryDelete" CommandName="QueryDelete"
CommandArgument='<%# DataBinder.Eval(Container,"DataItem.QueryGuid") %>'
Width="10" Height="10" />
It loads properly. When I click on it, I expect to hit the following codebehind method:
protected void QueryDelete(object sender, EventArgs e)
{
/* A bunch of code*/
}
It never gets there. What is more fustrating is that if I replace the ImageButton with
<asp:LinkButton ID="ImageButton_DeleteRun" Text="X"
runat="server" OnClick="QueryDelete" CommandName="QueryDelete"
CommandArgument='<%# DataBinder.Eval(Container,"DataItem.QueryGuid") %>'/>
It works perfectly.
Is there something wrong with ImageButton? Am I missing something?
EDIT - New info
Basically when the image button is rendered, there is no href.
Weird--
<input type="image" style="height: 10px; width: 10px; border-width: 0px;" src="../Assets/Images/Misc/delete.jpg"
id="ctl00_ctl00_ctl00_AllContent_MainContent_MainContent_controlPanelQueryHistory_saved_RadGridQueryHistory_ctl00_ctl04_ImageButton1"
name="ctl00$ctl00$ctl00$AllContent$MainContent$MainContent$controlPanelQueryHistory_saved$RadGridQueryHistory$ctl00$ctl04$ImageButton1"/>
<a
href="javascript:__doPostBack('ctl00$ctl00$ctl00$AllContent$MainContent$MainContent$controlPanelQueryHistory_saved$RadGridQueryHistory$ctl00$ctl04$ImageButton_DeleteRun','')"
id="ctl00_ctl00_ctl00_AllContent_MainContent_MainContent_controlPanelQueryHistory_saved_RadGridQueryHistory_ctl00_ctl04_ImageButton_DeleteRun">delete</a>
As a work around you could try wrapping an image within a LinkButton.
<asp:LinkButton ID="ImageButton_DeleteRun" Text="X"
runat="server" OnClick="QueryDelete" CommandName="QueryDelete"
CommandArgument='<%# DataBinder.Eval(Container,"DataItem.QueryGuid") %>'>
<img src="~/Assets/Images/Misc/delete.png" />
</asp:LinkButton>
Maybe the page is validating? If so, try adding CausesValidation=false to the ImageButton.
You may want to try replacing OnClick with OnCommand to see if that solves the problem.
Silly question - but is the ImageUrl rendering a valid image or red-x?
Put both link types in the page and then "View Source" on the resulting page. This may give you some clues as to what is happening. It may be rendering the ImageButton in a way that JavaScript or CSS is messing up.
How do you get the command arguments in OnClick? You have an EventArgs.
The OnCommand handler has CommandEventArgs containing the CommandName and CommandArguments:
protected void image_Command(object sender, CommandEventArgs e)
{
}
It would make sense to use the OnCommand.

Disable the postback on an <ASP:LinkButton>

I have an ASP.NET linkbutton control on my form. I would like to use it for javascript on the client side and prevent it from posting back to the server. (I'd like to use the linkbutton control so I can skin it and disable it in some cases, so a straight up tag is not preferred).
How do I prevent it from posting back to the server?
ASPX code:
<asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
someID.Attributes.Add("onClick", "return false;");
}
}
What renders as HTML is:
<a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a>
In this case, what happens is the onclick functionality becomes your validator. If it is false, the "href" link is not executed; however, if it is true the href will get executed. This eliminates your post back.
This may sound like an unhelpful answer ... But why are you using a LinkButton for something purely client-side? Use a standard HTML anchor tag and set its onclick action to your Javascript.
If you need the server to generate the text of that link, then use an asp:Label as the content between the anchor's start and end tags.
If you need to dynamically change the script behavior based on server-side code, consider asp:Literal as a technique.
But unless you're doing server-side activity from the Click event of the LinkButton, there just doesn't seem to be much point to using it here.
You can do it too
...LinkButton ID="BtnForgotPassword" runat="server" OnClientClick="ChangeText('1');return false"...
And it stop the link button postback
Just set href="#"
<asp:LinkButton ID="myLink" runat="server" href="#">Click Me</asp:LinkButton>
I think you should investigate using a HyperLink control. It's a server-side control (so you can manipulate visibility and such from code), but it omits a regular ol' anchor tag and doesn't cause a postback.
Just been through this, the correct way to do it is to use:
OnClientClick
return false
as in the following example line of code:
<asp:LinkButton ID="lbtnNext" runat="server" OnClientClick="findAllOccurences(); return false;" />
In C#, you'd do something like this:
MyButton.Attributes.Add("onclick", "put your javascript here including... return false;");
Instead of implement the attribute:
public partial class _Default : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
someID.Attributes.Add("onClick", "return false;");
}}
Use:
OnClientClick="return false;"
inside of asp:LinkButton tag
To avoid refresh of page, if the return false is not working with asp:LinkButton use
href="javascript: void;"
or
href="#"
along with OnClientClick="return false;"
<asp:LinkButton ID="linkPrint" runat="server" CausesValidation="False" href="javascript: void;"
OnClientClick="javascript:self.print();return false;">Print</asp:LinkButton>
Above is code will call the browser print without refresh the page.
call java script function on onclick event.
Have you tried to use the OnClientClick?
var myLinkButton = new LinkButton { Text = "Click Here", OnClientClick = "JavaScript: return false;" };
<asp:LinkButton ID="someID" runat="server" Text="clicky" OnClientClick="JavaScript: return false;"></asp:LinkButton>
Something else you can do, if you want to preserve your scroll position is this:
<asp:LinkButton runat="server" id="someId" href="javascript: void;" Text="Click Me" />
Why not use an empty ajax update panel and wire the linkbutton's click event to it? This way only the update panel will get updated, thus avoiding a postback and allowing you to run your javascript
No one seems to be doing it like this:
createEventLinkButton.Attributes.Add("onClick", " if (this.innerHTML == 'Please Wait') { return false; } else { this.innerHTML='Please Wait'; }");
This seems to be the only way that works.
In the jquery ready function you can do something like below -
var hrefcode = $('a[id*=linkbutton]').attr('href').split(':');
var onclickcode = "javascript: if`(Condition()) {" + hrefcode[1] + ";}";
$('a[id*=linkbutton]').attr('href', onclickcode);
You might also want to have the client-side function return false.
<asp:LinkButton runat="server" id="button" Text="Click Me" OnClick="myfunction();return false;" AutoPostBack="false" />
You might also consider:
<span runat="server" id="clickableSpan" onclick="myfunction();" class="clickable">Click Me</span>
I use the clickable class to set things like pointer, color, etc. so that its appearance is similar to an anchor tag, but I don't have to worry about it getting posted back or having to do the href="javascript:void(0);" trick.
use html link instead of asp link and you can use label in between html link for server side
control

Resources