Razor 语法是否在 UI 标记中提供了引人注目的优势? [英] Does Razor syntax provide a compelling advantage in UI markup?

查看:15
本文介绍了Razor 语法是否在 UI 标记中提供了引人注目的优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Scott Guthrie 开始提到 Razor在他的博客上有一个 href="http://weblogs.asp.net/scottgu/archive/2010/10/22/asp-net-mvc-3-layouts.aspx">公平点,但我只是不确定它是否适合我的风格.

I notice Scott Guthrie is starting to mention Razor a fair bit on his blog but I'm just not that sure that it's a good fit for my style.

对于已经习惯了标准"类型的 ASP.Net 标记(内容占位符和内联代码)的人来说,这是一种相当陌生的风格,但感觉就像有很多额外的页面需要管理,标记不太清楚给我.

Granted it's a fairly unfamiliar style for someone who's pretty used to a "standard" sort of ASP.Net markup (content place holders and inline code), but it just feels like a lot of additional pages to manage and less clear markup to me.

其他人对此有何感受?您认为在搭建新的 MVC 页面时应该认真考虑这些问题,还是只是试图解决一个不存在的问题?

What are other peoples' feelings on it? Is it something that you believe should be seriously considered when scaffolding new MVC pages or is it just trying to solve a problem that doesn't exist?

推荐答案

[免责声明:我是 MVC 和 Razor 的 Microsoft 开发人员之一,所以我可能有点偏见:)]

[Disclaimer: I'm one of the Microsoft developers on MVC and Razor, so I might be a bit biased :)]

我们将 Razor 设计为一种简洁的模板语言,只使用最少的必要控制字符.我想说的是,与使用传统"代码的相同代码相比,您的大部分观点可以用更少的字符来表达.WebForms 语法.

We designed Razor to be a concise templating language that uses only the minimal necessary amount of control characters. I would say that large parts of your views can be expressed with fewer characters than the same code using the "traditional" WebForms syntax.

例如以下 ASPX 语法中的代码片段:

For example the following code snippet in ASPX syntax:

<% if(someCondition) { %>
  <ol>
  <% foreach(var item in Model) { %>
     <li><%: item.ToString() %></li>
  <% } %>
  </ol>
<% } %>

在 Razor 中可以表示如下:

Can be expressed as follows in Razor:

@if(someCondition) {
   <ol>
   @foreach(var item in Model) {
      <li>@item.ToString()</li>
   }
   </ol>
}

虽然 ASPX 版本有 21 个转换字符(<%%>),但 Razor 版本只有三个(@>)

While the ASPX version has 21 transition characters (the <% and %>), the Razor version has only three (@)

我想说Razor的优点如下:

I would say that the advantages of Razor are as follows:

  1. 简洁的语法,与您编写常规 C# 代码的方式非常相似(请查看 Phil Haack 最近发表的以下博客文章,将 Asxp 与 Razor 语法进行了比较:http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx)
  2. 输出的自动 HTML 编码(有助于保护您免受 html 注入攻击)
  3. 内置(虽然不是 100%)标记验证,可帮助您避免不平衡的标签

与页面相关的概念也很容易从您在 ASPX 中的内容映射出来

The page-related concepts also map easily from what you have in ASPX

  • 如您所见,仍然允许使用内联代码
  • 部分(可以是可选的)相当于内容占位符
  • 布局页面而不是母版页面
  • 完整视图和部分视图的概念是相同的
  • @functions { ... } 块而不是
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆