2009-07-01 59 views
0

我是新编写自定义控件。我有MyCustomControl.cs,在我的Render方法中,我想渲染大约50行JavaScript。做这件事的最好方法是使用作者?从自定义控件编写JavaScript

protected override void Render(HtmlTextWriter writer) 
     { 
      writer.write(@"<script type....rest of opening tag here"); 

      writer.Write(@" 
          function decode(s) 
          { 
           return s.replace(/&amp;/g, ""&"") 
           .replace(/&quot;/g, '""') 
           .replace(/&#039;/g, ""'"") 
           .replace(/&lt;/g, ""<"") 
           .replace(/&gt;/g, "">""); 
          };" 
      ); 

我打算再多加6个writer.Write写出更多的章节。这是在这个庄园中实际执行JavaScript编写的最佳方法吗?

或者我应该使用ClientScript.RegisterClientScriptBlock?那么人们在自定义控件中编写javascript的最佳做法或常见方式是什么? (我不是在谈论一个用户控件在这里!,自定义控制/班!)

我也想保留任何缩进可读性一旦它吐出/收视源时,呈现在客户端上。

回答

0

我提供的只是把常规的回发到答案。以下所有可以使用ScriptManager及其相应的方法来应用。

有几个方法可以做到这一点。您可以加载网络资源并参考它

// The Scripts namespace in this case would actually be a physical folder in your YourNamespace.CustomControlsNamespace 
// namespace. 
// Also the /Scripts/YourJavaScriptFile.js needs to have it's Build Action property set to Embedded Resource 
[assembly: WebResource("YourNamespace.CustomControlsNamespace.Scripts.YourJavaScriptFile.js", "text/javascript")] 
namespace YourNamespace.CustomControlsNamespace 
{ 
    public CustomControl() 
    { 
     ... 
    } 

    ... 

    protected override OnPreRender(EventArgs e) 
    { 
     ... 

     Type type = typeof(CustomControl); 
     string scriptUrl = Page.ClientScript.GetWebResourceUrl(type, "Acuity.Web.UI.WebControls.Scripts.accdaterange.js"); 
     string key = "yourKey"; 


       if (!Page.ClientScript.IsClientScriptIncludeRegistered(type, key)) 
       { 
        control.Page.ClientScript.RegisterClientScriptInclude(type, key, scriptUrl); 
       } 

       ... 
    } 

    ... 
} 

您还可以在自定义控件中引用外部脚本。

namespace YourNamespace.CustomControlsNamespace 
{ 
    public CustomControl() 
    { 
     ... 
    } 

    ... 

    protected override OnPreRender(EventArgs e) 
    { 
     ... 

     Type type = typeof(CustomControl); 
     string scriptUrl = Page.ResolveClientUrl("~/yourScriptsFolder/yourExternalScript.js"); 
     string key = "yourKey"; 


       if (!Page.ClientScript.IsClientScriptIncludeRegistered(type, key)) 
       { 
        control.Page.ClientScript.RegisterClientScriptInclude(type, key, scriptUrl); 
       } 

       ... 
    } 

    ... 
} 

取决于你想要打包它。嵌入式资源的优势在于,您可以保证此脚本始终处于您的自定义控件所在的程序集中。您很可能必须添加一些内联JavaScript来连接自定义控件。尝试尽可能少地做到这一点。您可以使用Page.ClientScript.RegisterClientScriptBlock(...)来完成此操作。您还希望避免硬编码脚本中自动生成的客户端ID。它们应该作为参数传递给客户端对象。

而且,一旦一切看起来不错,你应该压缩/再压缩你的外部JavaScript文件。我使用雅虎的YuiCompressor。但还有其他几个人。

你也应该投资一些时间到考虑使用JavaScript框架如jQuery做很多繁重的工作。现在就是这样。我稍后可能会补充一些,但这些是我现在的智慧话语。

+0

我们不需要回传。我只是吐出jQuery和一些常规的JavaScript以及一系列值。我将使用这些值的数组将JSON调用回到.ashx处理程序,以便获取一些数据来填充该jQuery控件。 – PositiveGuy 2009-07-01 12:06:05