Inline javascript in my Razor file. Can I include this "included" from an external file

I have javascript blocks that are small. I would like the same blocks to appear inside my code, but don't want to repeat them in every file. Is there a way that I can include in Razor code that doesn't include

<script src="@Url.Content("~/Scripts/small_script_block1.js")" type="text/javascript"></script> 

thank

+4
asp.net-mvc
May 8 '11 at 4:51
source share
3 answers

Another opportunity that will take me a few more minutes:

Create an extension method for HtmlHelper. In your cshtml file, it will look like this:

 @Html.InlineScriptBlock("~/scripts/small_script_block1.js") 

If you want, I can send you an implementation, but this idea may be all that you need. If not, add a comment and I will write it.

EDIT CODE Below (not really and not implied or provided :)

 public static class HtmlHelperExtensions { public static MvcHtmlString InlineScriptBlock<TModel>(this HtmlHelper<TModel> htmlHelper, string path) { var builder = new TagBuilder("script"); builder.Attributes.Add("type", "text/javascript"); var physicalPath = htmlHelper.ViewContext.RequestContext.HttpContext.Server.MapPath(path); if (File.Exists(physicalPath)) { builder.InnerHtml = File.ReadAllText(physicalPath); } return MvcHtmlString.Create(builder.ToString()); } } 

Keep in mind that if you drop this into your project, you will need to make the namespace visible to the views. Unlike ASP.NET WebForms, where you can provide markup at the top, Razor requires you to do this in the Web.config file in the Views folder.

 <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="Your.Namespace.Here.Extensions" /> </namespaces> </pages> 
+5
May 08 '11 at 5:15
source share

The syntax @RenderSection can be used.

 <head> @RenderSection( "JavaScript", optional : true) </head> 

somewhere in the body, add ..

 @section JavaScript { <script src="/Scripts/script.js" type="text/javascript"></script> } 

EDIT: Or, if you prefer inline, then as follows:

 @section JavaScript { <script type="text/javascript"> function doSomething() { } </script> } 
+5
May 08 '11 at 5:00
source share
 @RenderPage("_IncludeYourScriptsHere.cshtml") 

Create a partial view and paste into your tag.

+2
May 08 '11 at 5:00 a.m.
source share



All Articles