1

上下文:ASP.NET 3.5 / C#

你好,

我创建了一个用户控件

public partial class MyControl : UserControl
{
    // EDIT: example first used "UniqueId" as property name, which was wrong.
    public Guid MyId { get; set; }
    // ...
}

和这个示例用法

<uc1:MyControl 
    ID="myControl" 
    MyId="443CBF34-F75F-11DD-BE2F-68C555D89123"
    runat="server" />

脚步:

  • 将此控件添加到 Web 表单 (aspx)

预期结果:

  • 添加用户控件的 HTML,MyId 的唯一值(对应于 Guid.NewGuid())在设计时在 ASPX HTML 中设置为 MyId 属性值。

实际结果:

  • 添加了用户控件的 HTML,在设计时未在 HTML 中为 MyId 属性值设置唯一值。

如果这是不可能的:

  • 解决方法 1:是否可以使用服务器控件来实现此目的?如何?
  • 解决方法 2:是否可以使用 UserControl 设计模式任务来实现这一点?

澄清:

  • 持久化属性值不是问题,因为它不会因控件实例而更改,并且由 ASP.NET 通过 aspx 页面中的控件声明自动设置。
  • MyId 属性不需要在运行时呈现。

乙!

4

4 回答 4

1

Visual Studio .NET 中的自定义设计时控件功能

于 2009-11-05T19:43:31.167 回答
0

因此,您只想生成一个仅在设计时使用的唯一 ID?

为什么不覆盖 Object.GetHasCode();

然后将其作为财产曝光?

于 2009-03-03T01:31:21.180 回答
0

You have a couple problems here, but first I will answer your questions about the workarounds.

  1. No you are already using a server control.
  2. No design-mode is to just make the lives of the developer easy, it doesn't effect anything else

You have two problems here. There is already a property called UniqueID I don't know if you were trying to overload that, but the question wasn't clear. The second problem is that your UniqueID essentially not getting stored anywhere. Try the following code:

public Guid UniqueId {
    get { return (Guid)ViewState["MyUserControlUniqueId"]; }
    set { ViewState["MyUserControlUniqueId"] = value; }
}

That will store the GUID in the ViewState so that you can retrieve it on post backs.

Update: Given your comment you need to override/use this method to add attributes to the rendered content.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.addattributestorender.aspx

于 2009-02-12T14:20:55.400 回答
0

如果我正确理解您的问题,您将在您的用户控件上公开一个名为 MyId 的属性。这允许您在放置该控件的任何位置设置属性。

您还想要的是,呈现的 HTML 也包含此属性和值。

如果是这种情况,属性 MyId 不会传递给 HTML,这只是因为用户控件具有 MyId 作为属性,它在设计器中可见。

在您的用户控件中,您将定义要呈现的标记。例如,如果您有:

<asp:Panel runat="Server" Id="myControlDiv">Some other content</asp:Panel>

然后,您可以在您的控件中预渲染事件(或您选择的任何其他地方)放置

myControlDiv.Attributes.Add("MyId", SomeGuid.ToString())

然后它将在 HTML 中输出为

<div id="generatedID" MyID="443CBF34-F75F-11DD-BE2F-68C555D89123">Some other content</div>
于 2009-02-16T14:28:11.000 回答