Call code behind method from aspx page

i have an image tag like

<asp:Image ID="ImgProduct" runat="server"    ImageUrl='<%# FormatImageUrl("10")%>' />

and in code behind i have
a method like

protected string FormatImageUrl(string s)
{
return "image"+s;
}

when i rum the code i am expecting that an HTML image tag with src=”image10″
will render.

but nothing happens
why?
any clues?

i am in asp.net . not mvc

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

the <%# .. %> is applied only during data binding. One solution is to manually call DataBind()

Try

protected void Page_Load(object sender, EventArgs e)
{
        ImgProduct.DataBind();
}

Method 2

You have to call Page.DataBind() or Control.DataBind(). Otherwise the <%# %> blocks will not be evaluated.

Method 3

in the aspx page

<asp:Image ID="ImgProduct" runat="server" ondatabinding="ImgProduct_DataBinding" />

in the cs file use this

protected void Page_Load(object sender, EventArgs e)
{
    ImgProduct.DataBind();

}
protected void ImgProduct_DataBinding(object sender, EventArgs e)
{
    ImgProduct.ImageUrl = "Image pathe + name";
}

Method 4

Why do all the databinding stuff just try the below.

protected void Page_Load(object sender,EventArgs e)
{
    if(!IsPostBack)
    {
        ImgProduct.ImageUrl = FormatImageUrl("10");
    }
}

protected string FormatImageUrl(string s)
{
    return "image"+s;
}

I don’t understand, what difference does it make for you to databind it or write the code on code behind. Saving a few key strokes??
It would be rather very easy to also watch the Object on Codebehind rather than the Data Binding expression model


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x