开发者

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 fil开发者_如何学Pythone 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>


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


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.

e.g.

<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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜