2

In my code a user can like a post when they click on the following code:

<li><a href="#" runat="server" onserverclick="LikePost" class="icon fa-heart"><%# Eval("Likes") %></a></li>

This will run the function LikePost in the codebehind:

    public void LikePost(object sender, EventArgs e)
    {
        //like post whit given id using a database query
    }

but how can I give that function a parameter, because it needs the postid from the post that the user is going to like.

1 Answer 1

1

Instead of an HTML link, use an asp:LinkButton which has a CommandArgument property. Something like this:

<asp:LinkButton
    ID="LinkButton1"
    Text='<%#Eval("Likes")%>'
    CommandArgument='<%#Eval("ID")%>'
    OnCommand="LikePost" 
    CssClass="icon fa-heart"
    runat="server"/>

Then in your code-behind the signature takes a CommandEventArgs:

public void LikePost(Object sender, CommandEventArgs e) 
{
    // e.CommandArgument should contain the desired value
}
Sign up to request clarification or add additional context in comments.

5 Comments

I will try this, but this is not containing the class="icon fa-heart", and I need that to show the like button.
@LesleyPeters: You can add classes to ASP.NET controls with the CssClass property. I've updated the answer.
Is it also possible to add 2 parameters?
@LesleyPeters: There's a CommandName property you might be able to use for that purpose. Anything more complex may involve serializing a more complex object as the CommandArgument and then de-serializing it in the handler.
Thanks a lot, I only need 2 parameters so I could use CommandName for the secend parameter :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.