用到 Razor的時候一直都是能讓 View正常顯示就好,沒認真研究過,有時候寫出來自己都覺得醜…(遮臉)那就…整理一下吧。
參考連結:
- http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/
- http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx/
- http://prideparrot.com/blog/archive/2012/9/simplifying_html_generation_using_razor_templates
看連結就知道 lag很久了,2011…
有幾點之前沒注意到,
<div class="@className foo bar"></div>
When className = null
<div class="foo bar"></div> Notice the leading space in front of foo is removed.
空字串不會移除開頭的空白
====
<input type="checkbox" checked="@isChecked" />
When isChecked = true
<input type="checkbox" checked="checked" />
When isChecked = false
<input type="checkbox" />
還發現一個沒用過的東西:Templated Razor Delegates,用 C#跟 HTML組成的樣版(嗯…型別(?)是 Func<dynamic, HelperResult>)。
// 一般 func定義
Func<dynamic, HelperResult> myFunc = (param1) => { return null; };
// Templated Razor Delegates,只有一個 item參數
Func<dynamic, HelperResult> myFunc = @<html tag>@item</html tag>;
怎麼用…直接看 code吧!https://dotnetfiddle.net/rFK5ak#
@using System.Text;
@using System.Collections;
@functions {
public static IHtmlString Repeat(int times, Func<dynamic, HelperResult> template) {
StringBuilder builder = new StringBuilder();
for(int i = 0; i < times; i++) {
builder.Append(template(i));
}
return new HtmlString(builder.ToString());
}
public static HelperResult List(IEnumerable items, Func<dynamic, HelperResult> template) {
return new HelperResult(writer => {
foreach (var v1 in items) {
template(v1).WriteTo(writer);
}
});
}
}
@{
var items = new[] { "one", "two", "three" };
string myClass= null;
}
<!DOCTYPE html>
<html>
<head>
<title>Repeat Helper Demo</title>
</head>
<body>
<p class="@myClass c1 c2">Repeat Helper</p>
<ul>
@List(items,@<li>@item</li>)
@Repeat(3, @<li>@item</li>)
</ul>
</body>
</html>