Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline javascript in my Razor file - Can I have this "included" from an external file

Tags:

asp.net-mvc

I have javascript blocks that are small. I would like to have these same blocks appear inline in my code but don't want to repeat them in each file. Is there a way that I can "include" code into the Razor file that doesn't involve

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

Thanks

like image 853
JudyJ Avatar asked May 08 '11 04:05

JudyJ


2 Answers

Another possibility that will take me a few more minutes to write up:

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

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

If you want I can send you the implementation but that idea might be all you need. If not, add a comment and I'll write it up.

EDIT CODE Below (not pretty and no warranty implied or given :)

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 could 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>
like image 100
CodeMonkeyKing Avatar answered Oct 13 '22 01:10

CodeMonkeyKing


You can use the @RenderSection syntax.

<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>
}
like image 23
Leons Avatar answered Oct 13 '22 00:10

Leons