2011-07-22 19 views
0

私は特定のビューにのみ適用されるインラインJavaScriptを備えたASP.NET MVCアプリケーションを持っています。ViewizeのためのJavaScriptの外部化

すべてのJavaScriptをメインレイアウトページに置くと、すべてのページにIDが存在しないため、エラーメッセージが表示されます。

ビューごとにJavaScriptを外部化する方法はありますか?

+1

以下の答えが正しいことができます。しかし、完全性のために、別のオプションがあります - あなたのJavascriptチェックで、IDがnullの場合。 – Daveo

答えて

1

MVC 2を使用している場合は、コンテンツプレースホルダを使用できます。

// this goes in your master page in your head tag 
<asp:ContentPlaceHolder id="Script" runat="server"/> 

// this goes in your view -- not partial 
<asp:Content ID="Content1" ContentPlaceHolderID="script" runat="server"> 
    <script type="text/javascript" src="foo.js"></script> 
</asp:Content> 

thisを実行できます。

2

これは片道です。これはあなたの中にかみそりビューエンジン

を使用しているヘッドのタグの間にページをレイアウト

<head> 
@RenderSection("Head", required: false); 
</head> 

は、あなたのビューでセクションを作成し、その中にあなたのスクリプトタグをつけセクションを作成します。

@section Head 
{ 
    <script type="text/javascript"> 
     do some java script... 
    </script> 

} 

ライトボックスなどのように、そのページに固有の外部ライブラリを参照することもできます。

0

javascriptは 'ID'がnullまたは未定義であるかどうかをテストし、もしあればコードを起動しません。

1

HtmlHelper拡張機能を使用して、使用しているスクリプトを各コントローラアクションに登録し、「MasterPage」は登録されている各スクリプトを正しいスクリプトタグでレンダリングします。

のHtmlHelper:コントローラのアクションで

public static void RegisterScript(string path) 
    { 
     if (!HttpContext.Current.Items.Contains("RegisteredScripts")) 
      HttpContext.Current.Items.Add("RegisteredScripts", ";" + path); 
     else 
      HttpContext.Current.Items["RegisteredScripts"] = ";" + path; 
    } 

    public static MvcHtmlString RegisteredScripts(this HtmlHelper html) 
    { 
     var lines = new StringBuilder(); 
     if (html.ViewContext.HttpContext.Items.Contains("RegisteredScripts")) 
     { 
      foreach (var k in html.ViewContext.HttpContext.Items["RegisteredScripts"].ToString().Substring(1).Split(';')) 
      { 
       lines.Append(html.Script(k)); 
      } 
     } 

     return MvcHtmlString.Create(lines.ToString()); 
    } 

    // Helper-functions 
    public static MvcHtmlString Script(this HtmlHelper html, string path) 
    { 
     if (!ExistsInContext(html, path)) 
     { 
      return Render(html, "<script type=\"text/javascript\" src=\"{0}\"></script>", path); 
     } 
     return MvcHtmlString.Create(""); 
    } 
    private static bool ExistsInContext(HtmlHelper html, string path) 
    { 
     return html.ViewContext.HttpContext.Items.Contains(path); 
    } 

だけ呼び出す:

Helpers.HtmlHelpers.RegisterScript("~/Scripts/custom.js"); 

希望これは

関連する問題