from:http://www.mikesdotnetting.com/article/258/usage-of-the-at-sign-in-asp-net

Thursday, January 22, 2015 1:54 PM

The number of places where you might use or encounter the @ sign in ASP.NET has grown over the last few years and its exact purpose in all circumstances still seems to cause confusion. Here's an overview of the most common places that it crops up, and guidance on its correct usage.

Razor Syntax

Razor was launched as a new templating syntax with the introduction of the ASP.NET Web Pages framework. A new view engine was added to MVC 3 that makes use of Razor. Razor enables mixing server-side code with HTML mark up to generate an HTML response that the framework sends to the browser. The @ sign has four uses in Razor:

  • To open a code block
  • To denote an inline expression or statement
  • To render the value of variables
  • To render single lines of content that contain plain text or unmatched HTML tags

Code blocks are sections of C# code that do not include any output to be rendered. They are usually positioned at the top of the Web Page or View and typically contain the logic for processing a page in Web Pages, or simple view-specific instructions in MVC. Code block start with the @ sign followed by an opening curly brace, and end with a closing curly brace:

@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_EditLayout.cshtml";
}

The content within the code block is standard C# code. A common mistake is to prefix variables declared within the code block with the @ sign. This is not necessary.

Inline expressions or statements are snippets of C# code appearing within HTML. Most often, these are used to make decisions on what to render based on conditions, or to iterate collections for display to the browser:

<ul>
@foreach (var item in rows)
{
// do something
}
</ul>

Nested expressions or statements do not start with an @ sign...

<ul>
@foreach (var item in rows)
{
if (item.Equals(x))
{
// do something
}
}
</ul>

...unless they are separated from the outer expression or statement by unmatched tags

<ul>
@foreach (var item in rows)
{
<li>
@if (item.Equals(x))
{
// do something
}
</li>
}
</ul>

The @ sign is used in Razor to render the value of variables, expressions and statements to the browser:

@DateTime.Now <!-- renders the current time to the browser -->

@(someCondition ? x : y) <!-- renders the value of x or y to the browser –>

@Html.ActionLink("Back to List", "Index") <!-- renders a hyperlink -->

Variables within expressions and statements should not be prefixed with the @ sign.

If you wish to render plain text or unmatched tags while inside a statement block, you use the @ sign followed by a colon to tell Razor that what follows is not C# code:

@if (item == x) // plain text
{
@:The time is @DateTime.Now
}
@if (item == x) // unmatched tags
{
@:<ul>
}
else
{
@:<ol>
}

Identifiers

An identifier in C# is the name given to a namespace, class, variable, property, method, interface etc. Rules govern what makes a valid identifier. It is permitted to use a C# keyword as an identifier, but if you do, you must use the @sign to prevent compile time errors. You are advised against using a keyword as an identifier, but there are times when you cannot avoid doing so.

Some overloads of the HtmlHelper classes (Web Pages and MVC) accept an object to represent the HTML attributes to be rendered as part of the tag that the helper represents. The following example adds a styleattribute to a text input and sets its value to width:100%;:

@Html.TextBoxFor(model => model.FirstName, htmlAttributes: new { style = "width:100%;"})

When you do this, you are creating an anonymous type with a property called style to represent the HTML attributes. If you want to set the CSS class attribute via this method, you need to add a property to the anonymous type called class - which is a C# keyword. Therefore you must use the @ sign to enable the use ofclass in this case:

@Html.TextBoxFor(model => model.FirstName, htmlAttributes: new { @class = "full-width"})

A mistake I see repeated quite often in the ASP.NET forums is to apply the @ sign to all other properties of the anonymous type, which is just not necessary. Some people even think that the @ sign used here is part of the Razor syntax rules. It's not. It's usage here preceded Razor by a long way.

Verbatim String Literals

verbatim string literal in C# consists of the @ sign followed by a literal string in double quotes and terminated with a semi-colon e.g.

var s = @"Hello World";

Two benefits of using a verbatim string literal include the fact that you only need to escape double quotes (by doubling them); and the string can span multiple lines in code without requiring continuation characters. For these reasons, verbatim string literals are most suitable for representing paths (which may otherwise need their slashes escaping) and regular expression patterns (which also may otherwise require backslashes to be escaped).

Regex re = new Regex(@"\w\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\w");

They are also useful for representing large blocks of text if they need to be included in code in a readable manner, such as SQL statements that might be used in Web Pages applications:

var sql = @"SELECT
p.ProductName,
o.UnitPrice,
o.Quantity,
(o.UnitPrice * o.Quantity) - (o.UnitPrice * o.Quantity * o.Discount) As TotalCost
FROM OrderDetails o
INNER JOIN Products p ON o.ProductID = p.ProductID
WHERE o.OrderID = @0";

The use of the @ sign in this context once again has nothing to do with Razor syntax.

Summary

If you have ever wondered when and where you should be using the @ sign in your ASP.NET code, hopefully this article has helped to resolve your confusion.

Usage of the @ (at) sign in ASP.NET的更多相关文章

  1. 【无私分享:ASP.NET CORE 项目实战(第四章)】Code First 创建数据库和数据表

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 本章我们来介绍下Asp.net Core 使用 CodeFirst 创建数据库和表,通过 控制台 和 dotnet ef 两种 ...

  2. Oracle 基础知识

    SQLDevelop 1. 查看数据库版本 :  select  *  from   v$version; 2. 查看表结构:        desc     TABLE_NAME 3. 查看当前连接 ...

  3. Autofac Getting Started(默认的构造函数注入)

    https://autofaccn.readthedocs.io/en/latest/getting-started/index.html The basic pattern for integrat ...

  4. selenium的方法

    # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreeme ...

  5. ASP.NET之Jquery入门级别

    1.Jquery的简单介绍 1)Jquery由美国人John Resig创建.是继prototype之后又一个优秀的JavaScript框架. 2)JQuery能做什么?JQuery能做的普通的Dom ...

  6. ASP.NET MVC5+EF6+EasyUI 后台管理系统(54)-工作流设计-所有流程监控

    系列目录 先补充一个平面化登陆页面代码,自己更换喜欢的颜色背景 @using Apps.Common; @{ Layout = null; } <!DOCTYPE html> <ht ...

  7. ASP.NET Core 中文文档 第三章 原理(13)管理应用程序状态

    原文:Managing Application State 作者:Steve Smith 翻译:姚阿勇(Dr.Yao) 校对:高嵩 在 ASP.NET Core 中,有多种途径可以对应用程序的状态进行 ...

  8. IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API

    IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习之保护API. 使用IdentityServer4 来实现使用客户端凭据保护ASP.N ...

  9. [转]An introduction to OAuth 2.0 using Facebook in ASP.NET Core

    本文转自:http://andrewlock.net/an-introduction-to-oauth-2-using-facebook-in-asp-net-core/ This is the ne ...

随机推荐

  1. ASM概述

    ASM的全称是 Automatic Storage Management,ASM 是为存放oracle 数据文件而设计的一个volume manager 和 文件系统 管理的技术. ASM 支持ora ...

  2. 11g R2 rac linstener 监听配置

    两个节点host,ipvip ,scan的信息 #eth0-Public IP 162.12.0.1    cqltjcpt1 162.12.0.3    cqltjcpt2 #eth1 PRIVAT ...

  3. vim中多行注释和多行删除命令

      1.多行注释:   1. 首先按esc进入命令行模式下,按下Ctrl + v,进入列(也叫区块)模式;   2. 在行首使用上下键选择需要注释的多行;   3. 按下键盘(大写)“I”键,进入插入 ...

  4. python urllib和urllib3包

    urllib.request urllib当中使用最多的模块,涉及请求,响应,浏览器模拟,代理,cookie等功能. 1. 快速请求 urlopen返回对象提供一些基本方法: read 返回文本数据 ...

  5. Mongodb时间问题

    Java保存到mongodb当前时间,使用RoboMongo查看数据显示时间比当前时间少8个小时,这是客户端的问题. MongoDB中的Date类型数据只保存绝对时间值,不保存时区信息,因此“显示的时 ...

  6. C#泛型参数多线程与复杂参数多线程

    背景:最近用多线程用的比较多自己走了一些弯路,分享出来希望大家少走弯路,C#中的多线程有两个重载,一个是不带参数的,一个是带参数的,但是即便是带参数的多线程也不支持泛型,这使得使用泛型参数多线程的时候 ...

  7. Vue 简单的总结二

    表单输入绑定 数据双向绑定 v-model 绑定相同的属性 当属性变化绑定的标签内容也跟着变化 v-model 只能应用像在input textare select 标签 v-model.lazy 懒 ...

  8. Java微信公众平台开发(九)--关键字回复以及客服接口实现(该公众号暂时无法提供服务解决方案)

    转自:http://www.cuiyongzhi.com/post/47.html 我们在微信公众号的后台可以发现微信给我们制定了两种模式,一种是开发者模式(也就是我们一直在做的开发),还有一种模式是 ...

  9. Unity3D Asset 导入&导出

    [Unity3D Asset 导入&导出] 通过Assets->Export Package..菜单可以导出当前选中Assets.若没有选中Assets,则会导出全部assets. 在弹 ...

  10. java Web jsp页面的静态包含和动态包含

    现在有头 体 尾 三个jsp页面 top.jsp <%@ page language="java" contentType="text/html; charset= ...