例如,我有一个以下列方式创建的Web控件:
<dnwc:TestControl runat="server" CurrentSite="test"></dnwc:TestControl>
如何在代码中获取CurrentSite的值(TestControl.cs)?我试着通过这样做来获得价值:
this.Attributes["CurrentSite"]
但是该值为空。
SOLUTION:
由于我无法发布答案,我将在此处添加。
我必须在TestControl.cs文件中声明该属性:
public string CurrentSite
{
get
{
string s = (string)ViewState["CurrentSite"];
return (s == null) ? "test2" : s;
}
set
{
ViewState["CurrentSite"] = value;
//Retrieve the current site and set it as an attribute in the input tag
inputTag.SetAttribute("data-current-site", value);
}
}
不幸的是我只能在设置后访问该值。在创建实例后设置该值。所以在构造函数被调用之后。最初我需要在构造函数调用的方法中设置值,但现在这样做。
答案 0 :(得分:1)
1)为WebControl
<dnwc:TestControl runat="server" CurrentSite="test" ID="testControl"></dnwc:TestControl>
2)您可以使用Page.FindControl(string id)
从后面的网页代码中获取Control
Control webcontrol = FindControl("testControl");
2)将Control
投射到TestControl
并获取CurrentSite
属性值。
string currentSite = ((TestControl)webcontrol).CurrentSite;