2011-11-30 177 views
0

我想創建這樣的app_code文件夾下一個asp.net MVC 3剃鬚刀幫手的定義:system.web.mvc.htmlhelper不包含的內容

@using System.Web.Mvc; 

@helper Script(string scriptName, System.Web.Mvc.HtmlHelper url){  
     <script src="@url.Content"~/Scripts/" + scriptName)" type="text/javascript"></script> 
} 

,但我得到錯誤:

system.web.mvc.htmlhelper不包含的內容

的定義在以下行:

<script src="@url.Content"~/Scripts/" + scriptName)" type="text/javascript"></script> 

回答

1

的錯誤是令人驚訝的有益的 - 的HtmlHelper不包含方法的內容(),該UrlHelper一樣。試試這個:

@helper Script(string scriptName, System.Web.Mvc.UrlHelper url){  
    <script src='@url.Content("~/Scripts/" + scriptName)' type="text/javascript"></script> 
} 
0

你可以這樣做,但這只是在一個視圖中可用。

如果你想從其它視圖訪問這個你應該寫像一個真正的HtmlHelper

的HtmlHelper樣品

創建靜態類

public static class TestClass 
{ 
    public static IHtmlString Script(this HtmlHelper helper, string script) 
    { 
     // if you need the UrlHelper do this 
     // var urlHelper = new UrlHelper(helper.ViewContext.RequestContext); 
     return new HtmlString(string.Format("<script src=\"~/Scripts/{0}\" type=\"text/javascript\"></script>", script)); 
    } 
} 

那麼你可以從您的視圖調用它(s)

@Html.Script("jquery-1.5.1.js") 

確保您查看知道您的班級所在的命名空間。

希望這有助於

+0

嗨:感謝您的回覆。但是我發佈的代碼有什麼問題。它來自於asp.net MVC 3網站上的視頻http://www.pluralsight-training.net/microsoft/players/PSODPlayer?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=0&course=aspdotnet-mvc3-intro – DotnetSparrow

+0

我更新了我的答案,也許這可以幫助你...我現在看看視頻 – dknaack

+0

你可以在一個視圖內以你想要的方式做到這一點。如果你想從其他視圖訪問,你應該在我的答案中寫一個真正的HtmlHelper。 – dknaack

0

我不知道爲什麼,但它不適合我。 運行完所有的jQuery控件不起作用,但在源代碼中我看到它。

,如果我嘗試包括

<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"> </script> 

工作的所有控制。