Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add custom code snippets for Razor pages (cshtml) in VS

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

like image 409
SteinTheRuler Avatar asked Oct 28 '25 11:10

SteinTheRuler


2 Answers

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:

  • Either type @ or @( to open an explicit statement
  • type foreach
  • type tab twice to activate the snippet

To edit the snippets, press Ctrl+K, Ctrl+B

like image 73
Marco Avatar answered Oct 31 '25 09:10

Marco


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>

  1. Tools > Code Snippet Manager > Language Dropdown: html > Import
  2. Navigation to your .snippet file and open
  3. Select both My HTML Snippets & HTML

enter image description here

  1. Select Finish and OK
  2. Open a cshtml file and type in your ShortCutName > hit tab

You should see your snippet in the cshtml, since language is html, and not CSharp, no need to open a code block

like image 32
Andrea Avatar answered Oct 31 '25 11:10

Andrea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!