How can I assign a callback function to an asp:HyperlinkField? - asp.net

I want people to click on a link (generated from an asp:HyperlinkField) and have it call a method on the server rather than redirect the user somewhere. Anyone know how to do this?
Thanks,
Matt

I'd use an asp:CommandField or asp:ButtonField instead and use ButtonType=Link - that will look the same as your linkfield, and then you can handle the OnRowCommand event in your grid to run your code.

Use an asp:LinkButton instead. Unless there's a particular reason you're attached to the asp:Hyperlink?

HyperLinkField is used for generating simple hyperlinks in databound controls. Instead you can use ButtonField. Or you can define your own link with TemplateField.
Here is a sample of generating link column which has a server side event :
<asp:templatefield headertext="Link Column">
<itemtemplate>
<asp:LinkButton ID="myLink"
CommandName="MyLinkCommand"
CommandArgument='<%#Bind("TableID") %>'
runat="server">My Link</asp:LinkButton>
</itemtemplate>
</asp:templatefield>
At code behind :
protected void YouGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyLinkCommand")
{
// Do stuff
}
}

Why not use a ButtonField instead and set the ButtonType property to a Link? It will look just like a hyperlink.

Related

how to use images in the asp:gridview using asp.net?

How to use images in grid view using asp.net?
Actually i want use images in the place of text for example in the place of Edit and Delete i want use some images related to text. Is that possible to use images please help me
Please define your template like this way
<asp:TemplateField HeaderStyle-Width="40">
<ItemTemplate>
<asp:ImageButton ID="ButtonDelete" runat="server"
ImageUrl="~/Imags/delete.png" OnClick="ButtonDelete_Click" ToolTip="Delete"
CommandArgument='<%#Bind("UserId")%>'/>
</ItemTemplate>
</asp:TemplateField>
Code Behind
protected void ButtonDelete_Click(object sender, EventArgs e)
{
ImageButton button = sender as ImageButton;
DeleteUserById(Convert.ToInt32(button.CommandArgument));
}

ASP.NET call a function in code behind with LinkButton

I have this LinkButton here
<asp:LinkButton runat="server" ID="EditBtn" CssClass="LinkButton" Text="Edit" Width="45px" OnClientClick="Profiles_Edit" CommandName="edit" />
and I am trying to call this function in my code behind
protected void Profiles_Edit(Object sender, ListViewCommandEventArgs e)
{
//do something
}
but when I click on the button....nothing happens. My LinkButton is inside an ItemTemplate, which is inside a ListView, which is inside a ContentTemplate, which is inside a UpdatePanel....
What is wrong with the way I am calling it?
Thanks,
J
OnClientClick is for specifying the name of the JavaScript function on the client browser.
To call the server-side event, use OnClick.
Also, you may not need the CommandName attribute in this situation. It isn't clear where this LinkButton resides. If it's in a container like a ListView, you would handle it differently.

How to hide link button based on a result returned by a class ?

I am bit new to C# and got a question.
I have a class as below that simply return false ( this is just to test)
public class SetAuthority
{
public SetAuthority()
{
//
// TODO: Add constructor logic here
//
}
public static Boolean AuthorizedToAddEdit()
{
return false;
}
}
I have a DetailsView with two link buttons to Edit and add New record. I want to hide the link buttons based on the above class method returning value.
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="New" Text="New"></asp:LinkButton>
</ItemTemplate>
Above works file and Edit and New link buttons are hidden when I run the program.
But the question is, I have a separate link button outside of the DetailsView. It is just a link to navigate to another page. I want to hide this in similar way using the same logic. I have the below code in my webform.
<asp:LinkButton ID="LinkButton5" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="OpenAdminPage" Text="Open Admin Page"></asp:LinkButton>
But the link button is always visible and seems it is not calling the class and not getting the value back. It appeared to be the class not return any value and can someone help me to identify what is the different between having this and working in DetailsView and not working for a simple link button.
Note: have a workaround where I can call the same method in Page Load event that works fine without any issue. Code is below
protected void Page_Load(object sender, EventArgs e)
{
Boolean myAllowAdd;
myAllowAdd = SetAuthority.AuthorizedToAddEdit();
if (myAllowAdd == false)
{
LinkButton1.Visible = false;
}
}
The reason is that this is for databinding expressions only: <%# Since the DetailsView is databound it works there.
If you would DataBind the page it worked also for the LinkButton outside of the DetailsView:
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
inline asp.net tags... sorting them all out (<%$, <%=, <%, <%#, etc.)
Side-note: be careful with static in ASP.NET. The static method does not yet hurt. But if you'd also use static fields you'd enter a minefield since it would be shared across all requests. Your current code-behind "work-around" is the better approach anyway.

ASP.Net repeater Item Command not getting fired

OK, I've used repeaters literally hundreds of times without problems but something has gone awry today. I have a repeater and I'm subscribing to the itemCommand event, but when my command runs, the page posts back but the event isn't fired.
To get around this I'm having to do my databinding on each postback.
My repeater looks like this:
<asp:Repeater id="MyRepeater" runat="server" onitemcommand="MyRepeater_ItemCommand">
<ItemTemplate>
<li>
<asp:Label id="Label" runat="server" />
<asp:LinkButton id="LinkButton1" runat="server" commandname="Complete" commandargument='<%# Eval("MyID") %>' text='<%# Eval("Title") %>' />
</li>
</ItemTemplate>
</asp:Repeater>
and my codebehind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetupPage();
}
}
private void SetupPage()
{
// Do other stuff
MyRepeater.DataSource = Repository.GetStuff()
MyRepeater.DataBind();
}
protected void MyRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
// Do all my stuff here
}
MyRepeater_ItemCommand is not getting called unless I comment out the if (!IsPostBack) line. Once that is commented out and the repeater is getting databound on each postback it works OK. I've done this in so many other pages but on this on it just doesn't seem to work.
Anyone else come across this behaviour or have a solution?
Most likely, you have disabled ViewState for the page.
The reason is that when you execute the postback, all the controls in the repeater are rebuild from the data in the viewstate normally. Then the object that should receive the event is identified based on the ID of the control, and the event is routed.
If you disable the viewstate, the control tree is not rebuild during postback, and therefore the control that should receive the event does not exist in memory. So the event dies.
If you really want to disable the viewstate, but still want to receive the event, I have a workaround (and it's not dirty at all). I've long been thinking about writing a blog entry about it, so if you want, I can take a bit time off my normal chores, and describe it.
Edit: The workaround is described here: http://petesdotnet.blogspot.dk/2009/08/asp.html
Remove if (!IsPostBack) as this is preventing the repeater from rebinding,
and the item command event could not find the row after postback.
I have the same problem and aside from using update panel, I have a required field validator in my modal. I found out that the LinkButtons in my repeater triggers the requiredFieldValidor event and then I added CausesValidation="false" in the LinkButtons of my repeater. Works as expected.
I have this problem in a repeater when I use ImageButton ...
I have search the net for this solution when LinkButton work, but not ImageButton ...
Then I think, LinkButton work? so i will use it :)
<asp:LinkButton CommandName="Filter" CommandArgument='<%# Eval("ID") %>' Text="" runat="server" >
<asp:image imageurl='<%#Eval("Img") %>' runat="server"/>
</asp:LinkButton>
So, the image is inside the <A> tag
have fun :)
I removed PostBackUrl property in linkbutton and ItemCommand fired. I think postback runs first.
That may be you have set Validations on your page. So set an new attribute, causevaliation = "false" to Link button. M sure it will solve the problem
I had a similar issue - turned out some discreet validation controls were firing elsewhere on the page. It only took me a day to figure it out ...
I am not positive about this, but you might have to set the CommandName and optionally CommandArgument properties for the button causing the ItemCommand event. Otherwise ASP.NET would assume that there is no button on the page, which you'd like to fire the event. You can try that.
Plus, if you're not differentiating between command names, why not use each button's Click event instead? Just subscribe to those in the repeater's ItemCreated or ItemDataBound.
Try using Page_init instead of Page_load and that should fix the problem.
Try this:
protected void Page_Load(object sender, EventArgs e)
{
SetupPage();
}
If you use nested-repeater, you should rebind your inner repe
Here Is the code you have to use in code behind..
after PageLoad event,
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
// Bind Your Repeater here
rptUser();
}
now you can fire your Itemcommand..if you get Output please mark answer as right thanks
One other thing that it could be (as it just happened to me): if your databind takes place when your page is prerendered, it won't process the item command. Switch it to load or init and you'll be fine.

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