Is it possible to add custom code snippets for Razor pages using the Code Snippets Manager in Visual Studio?
I can add snippets for HTML, but I can't find CSHTML anywhere.
I'm using Visual Studio Community 2019 16.4.1
That is because there are no dedicated Cshtml snippets. The Razor code is either C# or VB, so those snippets will be valid in a code block. To use those snippets you simply have to open a code-block:
@ or @( to open an explicit statementforeachTo edit the snippets, press Ctrl+K, Ctrl+B
This worked for me in Visual Studio 2019
Create and save your XML .snippet file. Example template:
<CodeSnippet Format="1.1.0">
<Header>
<Title>NameOfSnippet</Title>
<Author>YourName</Author>
<Shortcut>ShortCutName</Shortcut>
<Description>Description</Description>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>Id</ID>
<ToolTip>Please add an ID</ToolTip>
<Default>REPLACE_ID</Default>
</Literal>
</Declarations>
<Code Language="html"><![CDATA[<div id="$Id$">Example HTML Snippet</div>$end$]]></Code>
</Snippet>
You should see your snippet in the cshtml, since language is html, and not CSharp, no need to open a code block
When I was trying to tackle this problem, the thing that was missing in my mental model was that a .cshtml file consists of multiple parts that are in their own language context. For example, you could have:
<style></style> block that its contents would be css and VS would recognize CSS snippets in there,<script></script> block that has javascript content and VS would recognize javascript snippets@ block where vs could recognize either CSharp or Basic snippetsIn my case, I wanted to add a javascript snippet but I thought that the available snippets were tied directly with my file type so I was trying to add them as HTML snippets (and then was disappointed when they didn't show up in my script tag).
ALSO, its important to note that at least with VS 2017, you may need to restart VS to get the editor to recognize any new snippets.