简体   繁体   中英

How to use c# code inside <% … %> tags on asp.net page?

I'm writing an asp.net user control. It has a property, FurtherReadingPage, and two controls bound to it: ObjectDataSource and a Repeater. Inside the Repeater I would like to display a hyperlink with an href property set to something like FurtherReadingPage + "?id=" + Eval("Id") . I don't know how to do it inside the page's markup. I can use <% Eval("Id") %> or <% Response.Write(FurtherReadingPage + "?id=") %> alone but I don't know how to mix them.

You have a couple of different tags:

<% executes the code inside:

<% int id = int.Parse(Request["id"]); %> 

<%= writes out the code inside:

<%=id %> <!-- note no ; -->

<!-- this is shorthand for: -->
<% Response.Write(id); %> 

Both of these break up the normal flow when rendered on a page, for instance if you use them in a normal Asp.net <head runat="server"> you'll get problems.

<%# databinding:

<%# Eval("id") %>

This allows you to specify the bindings for controls that Asp.net WebForms render as a collection (rather than the literal controls that you can use <%= with), for instance:

<!-- this could be inside a repeater or another control -->
<asp:Hyperlink runat="server" ID="demo" 
     NavigateUrl="page.aspx?id=<%# Eval("id") %>" />

<%  //without this bind the <%# will be ignored
    void Page_Load( object sender, EventArgs e ) {
        demo.DataBind(); 
        //or
        repeaterWithManyLinks.DataBind(); 
    } 
%>

For your specific case you either:

  • Use a repeater and <%# Eval(...) %> with repeater.DataBind();

or

  • Use a foreach loop ( <% foreach(... %> ) with <%= ... %>

试试这个:

<%#String.Format("{0}?id={1}",FurtherReadingPage, Id)%>

你可以这样做 -

<asp:Hyperlink runat="Server" ID="hlLink" NavigateUrl='<%# FurtherReadingPage + "?Id=" + DataBinder.Eval(Container.DataItem, "Id")  %>' />

试试这个(例如链接): <a href='<%=FurtherReadingPage %>?id=<%# Eval("Id") %>'>My link</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM