Anyone have a good solution for formatting Razor files inside of VSCode? I've tried making it work with prettify-vscode and beautify. But in both cases it can't tell that cshtml files. I don't want to change my razor to html as I'll lose a lot of the razor-ness.
You can introduce them as HTML files (File -> Preferences -> Settings) without any 3rd party extensions:
{
"editor.formatOnSave": true,
"emmet.includeLanguages": {
"aspnetcorerazor": "html"
},
"files.associations": {
"*.cshtml": "html"
}
}
Update: v1.17.0 of C# for Visual Studio Code
add-on added preview Razor (cshtml) language service with support for C# completions and diagnostics.
formatOnSave
working with prettier, you can add "files.associations": {"*.cshtml": "html"}
to your preferences JSON and have cshtml prettier-ed too." Sound right? And where side-effects might files.assocations
cause? Is it prettier specific? (Appears not to be prettier specific and might very well have side effects.) –
Krisha There is an extension that we can switch between Language Modes by shortcuts quickly: changeLanguageMode.change
I use these shortcuts for js, html, and cshtml:
{
"key":"ctrl+k j",
"command":"changeLanguageMode.change",
"args": {
"languageId":"javascript"
}
},
{
"key":"ctrl+k h",
"command":"changeLanguageMode.change",
"args": {
"languageId":"html"
}
},
{
"key":"ctrl+k k",
"command":"changeLanguageMode.change",
"args": {
"languageId":"aspnetcorerazor"
}
}
To open keybindings.json
and add these shortcuts:
open up the control palette with CTRL +SHIFT + P and select Preferences: Open Keyboard Shortcuts File
.
Then use Ctrl + K, Ctrl + F to Format Selection only.
Change language mode deprecated in favor of Commands. To achieve the same functionality, you can define two commands inside your settings.json:
"commands.commands": {
"commands.changeLanguageRazor": {
"command": "commands.setEditorLanguage",
"args": "aspnetcorerazor"
},
"commands.changeLanguageHtml": {
"command": "commands.setEditorLanguage",
"args": "html"
},
},
These commands will allow you to switch between Razor and HTML language modes easily. Then, in your keybindings.json, create a command sequence:
{
"key": "shift+alt+f r",
"command": "runCommands",
"args": {
"commands": [
"commands.changeLanguageHtml",
"editor.action.formatDocument",
"commands.changeLanguageRazor"
]
},
"when": "editorTextFocus",
},
This command sequence initially sets the editor language to HTML, formats the document, and then switches back to Razor language mode.
Firstly: open file setting.json, which is in .vscode folder, then add next block:
{
"editor.formatOnSave": true,
"emmet.includeLanguages": {
"razor": "html"
},
"files.associations": {
"*.cshtml": "html"
}
Sometimes is necessary restart vscode
Finally: in the file to format Ctrl + k , Ctrl + f
© 2022 - 2025 — McMap. All rights reserved.