from:http://www.mikepope.com/blog/AddComment.aspx?blogid=2353

March 01, 2012

The beta release of ASP.NET Web Pages has been released (for example, as part of the ASP.NET MVC 4 Beta release). There are only a few differences from the December 2011 Developer Preview release. (Details when we've got them posted.)

A very cool feature is what's being called conditional attributes. The idea is that in markup, you can set the value of an element's attribute to a variable or expression. If the variable or expression returns false or null, the entire attribute is not rendered. There are a variety of uses for this, but it does a great job of solving a problem we inherited from HTML 1.0 (I think it was).

The problem manifests in cases where the simple appearance of an attribute name — regardless of its value — is sufficient to trigger HTML behavior. One case is the checkbox, i.e., the<input type="checkbox"> element:

<input type="checkbox" name="check1" value="check1" checked />
<input type="checkbox" name="check1" value="check1" checked="true" />
<input type="checkbox" name="check1" value="check1" checked="anyThingAtAll" />

Notice that in the first one, the checked attribute doesn't even have a value. Nonetheless, all of these work the same, namely they produce checkbox that's selected.

There's a similar situation with items in a selection list:

<select>
<option value="A">A</option>
<option value="B" selected>B</option>
<option value="C">C</option>
</select>

Technically, to select item B, the tag should read <option value="B" selected="selected">, but just including the selected attribute works.

All of this presents a problem when you want to use code in ASP.NET Web Pages to check a checkbox or select a list item. To just set a normal attribute value, you can use inline Razor code like this:

<input type="text" name="text1" value="@Request.Form["text1"]" />

But that doesn't work for the checked or selected attributes, since it doesn't matter what you set those attributes to.

The solution up to now has been to use more elaborate code in the page to render (or not render) the entire attribute, not just its value. Here's one example:

<input type="checkbox" name="check1" value="check1"
@if(Request.QueryString["val1"] == "true"){
<text>checked="checked"</text>
}
/>

Or if you were inclined, you could use the C# ternary operator, like this:

<input type="checkbox" name="check1" value="check1" 
@(Request.QueryString["val1"] == "true" ? Html.Raw("checked=\"checked\"") : null)
/>

Anyway, both of these methods were a little clunky.

It's now way simpler. As I say, you can now set an attribute to a code value, and if the value is true or non-null, the attribute renders. If it's false or null, the attribute doesn't render. Here's an example:

@{
bool check1 = false;
if(Request.QueryString["val1"] == "true"){
check1=true;
}
}

Then in the markup:

<input type="checkbox" name="check1" value="check1" checked="@check1" />

Magic.

You have to be careful that you don't assume that this works for all "truthy" and "falsy" values. For example, an empty string is not a false, so you can't return "" in order to kill the attribute. You could do something like this:

<input type="checkbox" name="check1" value="check1" 
checked=@(!(Request.QueryString["val1"].IsEmpty())) />

but this will render the attribute no matter what actual value ("true", "false", "foo") happens to be in the query string for val1.

Here's a page where you can see in a little more detail how this works. Pass query-string values like ?val1=true or ?val2=true to see what happens.

@{
bool checked1=false;
bool checked2=false;
Object someObject = null;
string aString = String.Empty; if(Request.QueryString["val1"] == "true"){
checked1=true;
} if(Request.QueryString["val2"] == "true"){
checked2=true;
someObject = this;
aString="Hello, conditional attributes!";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test Conditional Attributes</title>
</head>
<body> <form method="post"> <div>
<input type="checkbox" name="check1" value="check1" checked="@checked1" />
Value 1
<br/>
<input type="checkbox" name="check2" value="check2" checked="@checked2" />
Value 2
<br/>
<input type="checkbox" name="check3" value="check3" checked="@someObject" />
Some object
<br/>
<input type="checkbox" name="check4" value="check4" checked="@Request.Form["name"]" />
Request.Form["name"]
<br/>
<input type="checkbox" name="check5" value="check5" checked="@aString" />
aString
</div> <div>
<input type="submit" name="buttonSubmit" value="Submit" />
</div>
</form>
</body>
</html>

New for ASP.NET Web Pages: Conditional attributes的更多相关文章

  1. Announcing the Release of ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 for VS2012

    The NuGet packages for ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 are now live o ...

  2. ASP.NET Web Pages (Razor) API Quick Reference

    ASP.NET Web Pages (Razor) API Quick Reference By Tom FitzMacken|February 10, 2014 Print This page co ...

  3. 如何在ASP.NET Web站点中统一页面布局[Creating a Consistent Layout in ASP.NET Web Pages(Razor) Sites]

    如何在ASP.NET Web站点中统一页面布局[Creating a Consistent Layout in ASP.NET Web Pages(Razor) Sites] 一.布局页面介绍[Abo ...

  4. Displaying Data in a Chart with ASP.NET Web Pages (Razor)

    This article explains how to use a chart to display data in an ASP.NET Web Pages (Razor) website by ...

  5. 五张图概括 什么是 ASP 、 ASP.NET (Web Pages,Web Forms ,MVC )

    当你看懂下面这五张图,我相信你对于学习.NET Web开发路线将不陌生!                                               来源: http://www.w3 ...

  6. ASP.NET Web Pages 的冲突版本问题

    随着VS版本和.NET MVC版本.EF的版本的不断更新,虽然很多功能随着版本的提升而更完善,但对于旧版本开发的软件就有点悲催了,或许很多开发者都遇到类似的问题! 最近有一个项目是用.NET MVC3 ...

  7. ASP.NET Web Pages:C# 和 VB 实例

    ylbtech-.Net-ASP.NET Web Pages:C# 和 VB 实例 1.返回顶部 1. ASP.NET Web Pages - C# 和 VB 实例 通过 C# 和 Visual Ba ...

  8. ASP.NET Web Pages:发布网站

    ylbtech-.Net-ASP.NET Web Pages:发布网站 1.返回顶部 1. ASP.NET Web Pages - 发布网站 学习如何在不使用 WebMatrix 的情况下发布 Web ...

  9. ASP.NET Web Pages:PHP

    ylbtech-.Net-ASP.NET Web Pages:PHP 1.返回顶部 1. ASP.NET Web Pages - PHP PHP 开发人员请注意,Web Pages 可以用 PHP 编 ...

随机推荐

  1. Android 比对APK的签名信息

    https://www.jianshu.com/p/8583f6a966e2 在做App的时候经常会有验证apk是否为正版的需求,比如一些接入第三方支付的app,接入微信sdk也是需要apk签名信息的 ...

  2. (转)xshell基本操作步骤

    xshell  操作方法如下: mkdir +文件夹名   (新建目录) ls 文件浏览(使用ls命令列出文件列表的信息,默认情况下为当前目录下的所有文件,并按照字母顺序排列) file [选项].. ...

  3. sqlserver sql语句附加 分离数据库

    当使用 sp_attach_db 系统存储过程附加数据库时- - Tag: 当使用 sp_attach_db 系统存储过程附加数据库时 //附加数据库 sp_attach_db 当使用 sp_atta ...

  4. Java 数组的定义和遍历

    1.一维数组 数组是用来存储一组相同数据类型数据的数据结构 数组的元素可以是简单数据类型的数据,也可以是引用数据类型的数据 无论数组内容是简单类型还是引用类型,数组自己本身都是一种引用类型 每个数组元 ...

  5. erlang的dict和maps模块

    erlang在r17以后增加了map这个数据结构,在之前,类似map的需求用dict模块来实现,这里直接贴一下相关的操作 dict D = dict:new(). D1 = dict:store(k1 ...

  6. java 执行bat批处理文件 并关闭cmd窗口

    java 执行bat批处理文件 并关闭cmd窗口 import java.io.IOException; public class CmdMain { public static void main( ...

  7. 分布式缓存系统 Memcached 状态机之网络数据读取与解析

    整个状态机的基本流程如下图所示,后续分析将按该流程来进行. 接上节分解,主线程将接收的连接socket分发给了某工作线程,然后工作线程从任务队列中取出该连接socket的CQ_ITEM,开始处理该连接 ...

  8. PCB上 如何显示 汉字

    原理图上有汉字,那如何在PCB上显示汉子呢  ?  而不至于显示乱码 按如下操作  ,双击乱码  ,进入设置模式 设置好后,显示的字体样式.

  9. ThreadStart中带参数

    Thread Hand1 = new Thread(() =>        {            MethodName(参数1, 参数2);        });        Hand1 ...

  10. Py修行路 python基础 (七)文件操作 笔记(随时更改添加)

    文件操作流程: 1.打开文件 open() 2.操作文件 read .writeread(n) n对应读指定个数的 2.x中读取的是字节! 3.x中读取的是字符!read 往外读取文件,是以光标位置开 ...