C# Razor Syntax Quick Reference - ASP.NET MVC Razor 문법

2012. 9. 5. 11:07 개발언어/ASP.NET with MVC
C# Razor Syntax Quick Reference


ASP.NET MVC4 를 하면서 선행되어야 하는 공부가 있었습니다. 바로 Razor 문법 인데요. 로그인 처리후 앞단이 갱신될때 세션으로 로그인아이디를 검사하여 앞단 디자인을 갱신시에도 보여주어야 하는 것으로 지정을 해야 했는 데요.

기존에 웹폼에서는 <% %> 문법으로 처리하였다면 Razor 문법에서는 더욱 간결하게 @으로 처리할 수 있었습니다.

Index.cshtml 앞단 작성하기 

로그인 전에는 로그인해야 할 폼을 보여주고
로그인 후에 혹시 갱신이 되면 세션으로 현재의 상태를 확인하여 로그인 된 것으로 판단 되면 
로그인 된 후 적용되어야 하는 디자인을 보여주게 되어 있습니다.

이때 Razor 문법으로 비교 검새를 해주면 됩니다.



I gave a presentation to another team at Microsoft yesterday on ASP.NET MVC and the Razor view engine and someone asked if there was a reference for the Razor syntax.

It turns out, there is a pretty good guide about Razor available, but it’s focused on covering the basics of web programming using Razor and inline pages and not just the Razor syntax.

So I thought it might be handy to write up a a really concise quick reference about the Razor syntax.

Syntax/SampleRazorWeb Forms Equivalent (or remarks)
Code Block
  int x = 123; 
  string y = "because.";
  int x = 123; 
  string y = "because."; 
Expression (Html Encoded)
<span><%: model.Message %></span>
Expression (Unencoded)
@Html.Raw(model.Message) </span>
<span><%= model.Message %></span>
Combining Text and markup
@foreach(var item in items) {
<% foreach(var item in items) { %>
  <span><%: item.Prop %></span>
<% } %>
Mixing code and Plain text
@if (foo) {
  <text>Plain Text</text> 
<% if (foo) { %> 
  Plain Text 
<% } %>
Mixing code and plain text (alternate)
@if (foo) {
  @:Plain Text is @bar
Same as above
Email Addresses
Hi philha@example.com
Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter
Explicit Expression
In this case, we need to be explicit about the expression by using parentheses.
Escaping the @ sign
<span>In Razor, you use the 
@@foo to display the value 
of foo</span>
@@ renders a single @ in the response.
Server side Comment
This is a server side 
multiline comment 
This is a server side 
multiline comment
Calling generic method
Use parentheses to be explicit about what the expression is.
Creating a Razor Delegate
  Func<dynamic, object> b = 
@b("Bold this")
Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details.
Mixing expressions and text
Hello @title. @name.
Hello <%: title %>. <%: name %>.

Notice in the last example that Razor is smart enough to know that the ending period is a literal text punctuation and not meant to indicate that it’s trying to call a method or property of the expression.

Let me know if there are other examples you think should be placed in this guide. I hope you find this helpful.

■ 참고사이트
C# Razor Syntax Quick Reference :