简体   繁体   English

ASP.NET和C#中的自定义服务器控件 -

[英]Custom Server Control in ASP.NET and C# -

I've got a aspx and aspx.cs file with some components. 我有一些带有一些组件的aspx和aspx.cs文件。 Now I want to reuse parts of that page in another page. 现在我想在另一个页面中重用该页面的一部分。 My approach would be to pull out the duplicate part into a WebServerControl. 我的方法是将重复的部分拉出到WebServerControl中。

So before I waste more time yahoogling, is that even the right idea and if so, is there a way to use parts of the aspx file rather than doing it tediously in RenderContents with the HtmlTextWriter , WriteBeginTag , WriteAttribute and so on. 所以在我浪费更多时间yahoogling之前,即使是正确的想法,如果是这样,有没有办法使用部分aspx文件而不是在RenderContents使用HtmlTextWriterWriteBeginTagWriteAttribute等进行繁琐的操作。 That looks like a mess for complicated layout and sizeable amounts of controls. 对于复杂的布局和大量的控件来说,这看起来很混乱。

What's the standard? 标准是什么?

Depends. 要看。

The main driving factor is that if you need to reuse your control in multiple web applications, you should go with a Custom Control (.cs in C#). 主要驱动因素是,如果您需要在多个Web应用程序中重用控件,则应使用Custom Control (C#中的.cs)。

Else, if you only intend to reuse your control in one web application, choose a User Control (.ascx). 否则,如果您只打算在一个Web应用程序中重用控件,请选择User Control (.ascx)。

This MSDN article is a good starting point. 这篇 MSDN文章是一个很好的起点。

UPDATE (since OP asked further details): 更新(因为OP询问了进一步的细节):

To embed JavaScript for a custom control, a common approach is 要为自定义控件嵌入JavaScript,常见的方法是

var initializeScript = string.Format("MyNamespace.initialize('{0}', {1});", ClientID, myScriptString);
Attributes.Add("onmouseover", initializeScript);

Suggest to write JavaScript code in a js file and not in .cs since the latter is a nightmare to maintain and debug. 建议在js文件而不是.cs中编写JavaScript代码,因为后者是维护和调试的噩梦。 Hope this helps. 希望这可以帮助。

It sounds like what you want to do is bundle the items into a User Control . 听起来你想要做的就是将项目捆绑到用户控件中 This will allow you to design the control by using existing .NET controls rather than rendering everything out from scratch. 这将允许您使用现有的.NET控件设计控件,而不是从头开始渲染所有内容。

All you need is to create an ASP.NET Web User Control 您所需要的只是创建一个ASP.NET Web用户控件

Taken from MSDN: 摘自MSDN:

An ASP.NET Web user control is similar to a complete ASP.NET Web page (.aspx file), with both a user interface page and code. ASP.NET Web用户控件类似于完整的ASP.NET网页(.aspx文件),包含用户界面页面和代码。 You create the user control in much the same way you create an ASP.NET page and then add the markup and child controls that you need. 您创建用户控件的方式与创建ASP.NET页面的方式大致相同,然后添加所需的标记和子控件。 A user control can include code to manipulate its contents like a page can, including performing tasks such as data binding. 用户控件可以包括用于像页面一样操纵其内容的代码,包括执行诸如数据绑定之类的任务。

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

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