196

How to write a comment in a MVC view, that won't be transmitted to the final HTML (i.e.,to browser, to response). One can make a comment with:

<!--<a href="/">My comment</a> -->

but, it is visible in the page source code in browser.

Is it possible to leave comments in '.cshtml' files only for internal use?

Rahul Soni
  • 153
  • 3
  • 18
horgh
  • 17,918
  • 22
  • 68
  • 123

2 Answers2

342

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

mekb
  • 554
  • 8
  • 22
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • 3
    Forgot to try it))))) I usually use Ctrl+E,C and Ctrl+E,U. Thanks a lot – horgh Aug 29 '12 at 05:50
  • 1
    This response is incorrect. See the other response to this question. – Zackary Geers Apr 02 '18 at 17:48
  • 2
    @ZackaryGeers I'm not following - sobering's answer seems to have duplicated my original answer, and I've subsequently augmented to respond to the OP's concerns about keeping comments hidden for internal use. What is incorrect? – StuartLC May 24 '18 at 19:14
  • 2
    But I use the C# comment syntax (`//...`, `/*...*/`) in the Razor page. Shouldn't it actually be rendered as text? – mekb Aug 31 '19 at 12:55
  • 3
    It depends where you place the // comment. Razor can have C# sections (denoted by a starting @), Html and even JS sections Script sections. C# comments won't be echoed by the server. Comments in js and html will be sent to the browser.. // comments in Html will be regarded as text and will likely be visible to the end user. – StuartLC Sep 01 '19 at 06:12
30

This comment syntax should work for you:

@* enter comments here *@
sobering
  • 544
  • 4
  • 10