简体   繁体   English

评估主播href

[英]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: 但是当我运行页面时,href标记呈现为空字符串:

<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. 如果在模板(例如GridView的ItemTemplate )中使用数据绑定表达式 <%# ... %> ,则会自动调用数据绑定。 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): 但是,如果在模板之外使用此类表达式,则需要通过调用Control.DataBind() (或您的情况下的this.DataBind()来调用数据绑定。

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): 由于您使用的是基本HTML元素(而不是Web控件),因此可以只使用内联ASP.NET表达式(不需要this.DataBind() ):

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

In any case, make sure your link does not contain quotes ' , or you are in for some HTML injection. 无论如何,请确保您的链接不包含引号' ,或者您可以进行HTML注入。 If the value is supplied by the user, don't forget to HtmlEncode and sanitize it. 如果该值由用户提供,请不要忘记对HtmlEncode进行清理。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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