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.
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With