Search code examples
c#javascriptasp.net-mvc-3razor

How to embed Razor C# code in a .js file?


Have to embed javascript code block with

<script type='text/javascript'>
  ...
</script>

But Razor code won't compile in a .js file, included from a .cshtml file.

How to make this work? Or is there any other elegant way to have a similar effect?

Thank you.


Solution

  • When I face this problem sometimes I will provide a function in the .js file that is accessible in the .cshtml file...

    // someFile.js
    var myFunction = function(options){
        // do stuff with options
    };
    
    // razorFile.cshtml
    <script>
        window.myFunction = new myFunction(@model.Stuff);
        // If you need a whole model serialized then use...
        window.myFunction = new myFunction(@Html.Raw(Json.Encode(model)));
    </script>
    

    Not necessarily the BEST option, but it'll do if you have to do it...

    The other thing you could maybe try is using data attributes on your html elements like how jQuery.validate.unobtrusive does...

    //someFile.js
    var options = $("#stuff").data('stuff');
    
    // razorFile.cshtml
    <input type="hidden" id="stuff" data-stuff="@model.Stuff" />