Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating JavaScript in cshtml razor views

I'm new to ASP.NET/MVC3 and I'm trying to figure out how to separate my JavaScript (which contains C#) from the rest of the HTML.

If I put them into .JS files and insert them with a script tag then the C# aspect of them stops working. What is the best way of separating your JavaScript code that also contains C# code in MVC 3 razor?

Thanks.

like image 981
user1157885 Avatar asked Mar 13 '12 10:03

user1157885


People also ask

Can I use JavaScript in razor pages?

You can call JavaScript methods from the Blazor pages with the help of JavaScript Interop by injecting the dependency IJSRuntime into the razor page. Then refer the script in the HTML page of the blazor application. Check this link for more information.

Can you put JavaScript in a partial view?

JavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a @Html. Action helper method, as in this section from Edit.

What is the difference between Cshtml and razor?

razor helps you embed serverside code like C# code into web pages. cshtml is just a file extension. razor view engine is used to convert razor pages(. cshtml) to html.

Should I separate JavaScript files?

You should put your JS code in a separate file because this makes it easier to test and develop. The question of how you serve the code is a different matter. Serving the HTML and the JS separately has the advantage that a client can cache the JS.


1 Answers

For many reasons, you're better off putting most, if not all of your JS into separate JS files (so that you can take advantage of reuse, minification, browser optimizations, content delivery networks etc.)

To read the result of server-side razor code into your JS files use one of the following methods:

1) Put your razor code into a javascript variable in the view (not tested code)

<script type="text/javascript">
  if(!MyGlobalVariables){
     MyGlobalVariables = {};
  }
  MyGlobalVariables.IndexUrl = "@Url.Action("Index")";
</script>

2) Use a custom attribute (preferrably prefixed with data- as suggested in HTML 5 spec). See related discussion here: Can I add custom attribute to HTML tag?

<div data-index-url="@Url.Action("Index")"></div>

Then, use $(this).attr("data-index-url") in jQuery to access the rendered razor markup.

3) Put the C# into hidden input fields on your view, and read the hidden input in your JS file.

<input id="indexUrl" type="hidden" value="@Url.Action("Index")" />

To read this in jQuery, you would use $("#indexUrl").val()

like image 165
Zaid Masud Avatar answered Sep 21 '22 12:09

Zaid Masud