简体   繁体   中英

How to get visual studio to recognize a cshtml file as javascript

I am writing a css/js page that has some dynamic parts in it. To do this i am using a cshtml file containing css/js - i am using mvc.net and returning the css from a controller action.

The trouble is visual studio recognizes this page as html and not as javascript/css so it does not give me javascript/css coloring and IntelliSense.

My questions:

  1. is there a better/easier way of creating dynamic css/js in .net
  2. How can i get visual studio to recognize a cshtml page as javascript.

I know this is an old post...but...

What I did was just put the script tags around my javascript files in their own.cshtml file. I created a separate controller (JavascriptController.cs), and I created a filter on that controller that removes the script tags. I set the filter in the OnActionExecuting method. by just doing

this.Response.Filter = new ScriptFilter(Response.Filter, Response.ContentEncoding);

So you get the syntax, you get razor without having to use RazorJS, and you can request the js files like regular routes in an MVC application. You just have to keep the script tags on the partial view while editing.

So you can call

/Javascript/{Action}

and you'll get your javascript file with your razor in it, and the filter will remove the script tags so you can include it like a normal script.

<script src="http://{host}/Javascript/{action}"></script>

The best solution is to follow unobtrusive javascript and unobtrusive styling and put your javascript into a .js file, put your css into a .css file and reference them in the markup in your cshtml file with a <script> and <link> tag.

eg

<script src="Scripts/scriptName.js" type="text/javascript"></script>
<link rel="stylesheet" href="Content/styleSheetname.css" type="text/css" />

This is good practice as it keeps your content(markup)/styling/behaviour separate.

What is wrong with putting <script> and <style> tags in a page and put your dynamic js/css there, in the end if it is dynamic there is no way for caching it so this approach will be fine. you can write something like below:

<script>
 function myFunction_@MyFunc(params)(obj) {  return obj.field + @MyOtherFunc(params); }
<script>

and razor engine will evaluate @MyFunc(params) and @MyOtherFunc(params) before sending it to browser

For JavaScript you could try the RazorJS nuget package. But we've run into some inconsistencies while using it.

Still trying to find a better way to do this using Controller/Views and still be able to use intellisense and get decent coloring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM