简体   繁体   中英

Eval in anchor href

I have the following code behind:

protected string VcdControlPanelLink { get; set; }

protected void Page_Load(object sender, EventArgs e) {
    VcdControlPanelLink = "http://www.mywebsite.com";
}

And the following markup:

<a href='<%# Eval(VcdControlPanelLink) %>' target="_blank" title="View the VDC control panel">VDC control panel</a>

But when I run the page, the href tag is rendered as an empty string:

<a title="View the VDC control panel" target="_blank" href="">VDC control panel</a>

I have tried various combinations of markup etc, but cannot get it to work. What am i missing?

If you use data binding expressions <%# ... %> in templates (eg the ItemTemplate of a GridView), data binding is invoked automatically. However, if you use such expressions outside of templates, you need to invoke data binding yourself by calling Control.DataBind() (or this.DataBind() in your case):

protected string VcdControlPanelLink { get; set; }

protected void Page_Load(object sender, EventArgs e) {
    VcdControlPanelLink = "http://www.mywebsite.com";
    this.DataBind();
}

<!-- Note that you do *not* use Eval here! -->
<a href='<%# VcdControlPanelLink %>' target="_blank" ... />

However, I don't think data binding is the right tool here. Since you are using basic HTML elements (instead of web controls), you can just use an inline ASP.NET expression (no this.DataBind() required):

<a href='<%= VcdControlPanelLink %>' target="_blank" ... />

In any case, make sure your link does not contain quotes ' , or you are in for some HTML injection. If the value is supplied by the user, don't forget to HtmlEncode and sanitize it.

Make your property public and access it like this,

public string VcdControlPanelLink { get; set; }

<a href='<%= VcdControlPanelLink %>' target="_blank" title="View the VDC control panel">VDC control panel</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