Razor Syntax Reference
Implicit Razor expressions
<p>@DateTime.Now</p>
<p>@DateTime.IsLeapYear()</p>
<p>@await DoSomething("hello", "world")</p> Explicit Razor expressions
<p>Last week this time: @(DateTime.Now - TimeSpan.FromDays())</p>
@{
var joe = new Person("Joe", );
} <p>Age@(joe.Age)</p> Expression encoding
@("<span>Hello World</span>")
@Html.Raw("<span>Hello World</span>") Implicit transitions
@{
var inCSharp = true;
<p>Now in HTML, was in C# @inCSharp</p>
} Explicit delimited transition
@for (var i = ; i < people.Length; i++)
{
var person = people[i];
<text>Name: @person.Name</text>
@:Name: @person.Name//Explicit Line Transition with @:
} @try
{
throw new InvalidOperationException("You did something invalid.");
}
catch (Exception ex)
{
<p>The exception message: @ex.Message</p>
}
finally
{
<p>The finally statement.</p>
}
@lock (SomeLock)
{
// Do critical section work
} using Microsoft.AspNetCore.Mvc.Razor;
public abstract class CustomRazorPage<TModel> : RazorPage<TModel>
{
public string CustomText { get; } = "Hello World.";
}
@inherits CustomRazorPage<TModel> <div>Custom text: @CustomText</div> @functions {
public string GetHello()
{
return "Hello";
}
}
<div>From method: @GetHello()</div> Razor keywords
•functions
•inherits
•model
•section
•helper (Not supported by ASP.NET Core.) C# Razor keywords
•case
•do
•default
•for
•foreach
•if
•lock
•switch
•try
•using
•while ----------------------------------------------------------------------------------------------------
Layout The "_ViewImports" file supports the following directives:
•@addTagHelper, @removeTagHelper: all run, in order
•@tagHelperPrefix: the closest one to the view overrides any others
•@model: the closest one to the view overrides any others
•@inherits: the closest one to the view overrides any others
•@using: all are included; duplicates are ignored
•@inject: for each property, the closest one to the view overrides any others with the same property name -----------------------------------------------------------------------------------------------------
Working with Forms The Templates Path: ------------------------------------------------------------------------------------------------------
@model Person
@{
var index = (int)ViewData["index"];
} <form asp-controller="ToDo" asp-action="Edit" method="post">
@Html.EditorFor(m => m.Colors[index])
<label asp-for="Age"></label>
<input asp-for="Age" /><br />
<button type="submit">Post</button>
</form> Views/Shared/EditorTemplates/String.cshtml
@model string
<label asp-for="@Model"></label>
<input asp-for="@Model" /> <br /> -----------------------------------------------------------------------------------------------------
@model CountryViewModel
<form asp-controller="Home" asp-action="IndexEmpty" method="post">
@Html.EditorForModel()
<br /><button type="submit">Register</button>
</form> Views/Shared/EditorTemplates/CountryViewModel.cshtml
@model CountryViewModel
<select asp-for="Country" asp-items="Model.Countries">
<option value="">--none--</option>
</select>
---------------------------------------------------------------------------------------------------- Authoring Tag Helpers @using AuthoringTagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "AuthoringTagHelpers.TagHelpers.EmailTagHelper, AuthoringTagHelpers" <address>
<strong>Support:</strong><email mail-to="Support"></email><br />
<strong>Marketing:</strong><email mail-to="Marketing"></email>
</address> public class EmailTagHelper : TagHelper
{
private const string EmailDomain = "contoso.com"; // Can be passed via <email mail-to="..." />.
// Pascal case gets translated into lower-kebab-case.
//public string MailTo { get; set; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a";// Replaces <email> with <a> tag
//var address = MailTo + "@" + EmailDomain; var content = await output.GetChildContentAsync();
var target = content.GetContent() + "@" + EmailDomain;
output.Attributes.SetAttribute("href", "mailto:" + target);
output.Content.SetContent(target);
}
} [HtmlTargetElement("email", TagStructure = TagStructure.WithoutEndTag)]
public class EmailVoidTagHelper : TagHelper [HtmlTargetElement("Website-Information")]
public class WebsiteInformationTagHelper : TagHelper
{
public WebsiteContext Info { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "section";
output.Content.SetHtmlContent(
$@"<ul><li><strong>Version:</strong> {Info.Version}</li>
<li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
<li><strong>Approved:</strong> {Info.Approved}</li>
<li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
output.TagMode = TagMode.StartTagAndEndTag;
}
} <website-information info="new WebsiteContext {
Version = new Version(, ),
CopyrightYear = ,
Approved = true,
TagsToShow = }" /> [HtmlTargetElement(Attributes = nameof(Condition))]
public class ConditionTagHelper : TagHelper
{
public bool Condition { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!Condition)
{
output.SuppressOutput();
}
}
}
<div condition="Model.Approved">
<p>
This website has <strong surround="em"> @Model.Approved </strong> been approved yet.
Visit www.contoso.com for more information.
</p>
</div> public class AutoLinkerHttpTagHelper : TagHelper
{
// This filter must run before the AutoLinkerWwwTagHelper as it searches and replaces http and
// the AutoLinkerWwwTagHelper adds http to the markup.
public override int Order
{
get { return int.MinValue; }
} public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = output.Content.IsModified ? output.Content.GetContent() :
(await output.GetChildContentAsync()).GetContent(); // Find Urls in the content and replace them with their anchor tag equivalent.
output.Content.SetHtmlContent(Regex.Replace(
childContent,
@"\b(?:https?://)(\S+)\b",
"<a target=\"_blank\" href=\"$0\">$0</a>")); // http link version}
}
} [HtmlTargetElement("p")]
public class AutoLinkerWwwTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = output.Content.IsModified ? output.Content.GetContent() :
(await output.GetChildContentAsync()).GetContent(); // Find Urls in the content and replace them with their anchor tag equivalent.
output.Content.SetHtmlContent(Regex.Replace(
childContent,
@"\b(www\.)(\S+)\b",
"<a target=\"_blank\" href=\"http://$0\">$0</a>")); // www version
}
}
} ----------------------------------------------------------------------------------------------------
Partial Views @Html.Partial("AuthorPartial")
@await Html.PartialAsync("AuthorPartial")
@{
Html.RenderPartial("AuthorPartial");
} @Html.Partial("ViewName")
@Html.Partial("ViewName.cshtml")
@Html.Partial("~/Views/Folder/ViewName.cshtml")
@Html.Partial("/Views/Folder/ViewName.cshtml")
@Html.Partial("../Account/LoginPartial.cshtml") ---------------------------------------------------------------------------------------------------
View Components View search path:
•Views/<controller_name>/Components/<view_component_name>/<view_name>
•Views/Shared/Components/<view_component_name>/<view_name> <div >
@await Component.InvokeAsync("PriorityList", new { maxPriority = , isDone = false })
</div> public IActionResult IndexVC()
{
return ViewComponent("PriorityList", new { maxPriority = , isDone = false });
} //[ViewComponent(Name = "PriorityList")]
//public class XYZ : ViewComponent
public class PriorityListViewComponent : ViewComponent
{
private readonly ToDoContext db; public PriorityListViewComponent(ToDoContext context)
{
db = context;
} public async Task<IViewComponentResult> InvokeAsync(
int maxPriority, bool isDone)
{
string MyView = "Default";
// If asking for all completed tasks, render with the "PVC" view.
if (maxPriority > && isDone == true)
{
MyView = "PVC";
}
var items = await GetItemsAsync(maxPriority, isDone);
return View(MyView, items);
} private Task<List<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
{
return db.ToDo.Where(x => x.IsDone == isDone &&
x.Priority <= maxPriority).ToListAsync();
}
}
-----------------------------------------------------------------------------------------------

DotNETCore 学习笔记 MVC视图的更多相关文章

  1. 2.《Spring学习笔记-MVC》系列文章,讲解返回json数据的文章共有3篇,分别为:

    转自:https://www.cnblogs.com/ssslinppp/p/4528892.html 个人认为,使用@ResponseBody方式来实现json数据的返回比较方便,推荐使用. 摘要 ...

  2. Django:学习笔记(9)——视图

    Django:学习笔记(9)——视图 基础视图 基于函数的视图,我们需要在使用条件语句来判断请求类型,并分支处理.但是在基于类的视图中,我们可以在类中定义不同请求类型的方法来处理相对应的请求. 基于函 ...

  3. Django:学习笔记(8)——视图

    Django:学习笔记(8)——视图

  4. 3.《Spring学习笔记-MVC》系列文章,讲解返回json数据的文章共有3篇,分别为:

    转自:https://www.cnblogs.com/ssslinppp/p/4528892.html 概述 在文章:<[Spring学习笔记-MVC-3]SpringMVC返回Json数据-方 ...

  5. 1.《Spring学习笔记-MVC》系列文章,讲解返回json数据的文章共有3篇,分别为:

    转自:https://www.cnblogs.com/ssslinppp/p/4528892.html [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://w ...

  6. Oracle 学习笔记 11 -- 视图 (VIEW)

    本次必须学习一个全新的概念-- 视图 (VIEW).在前面的笔记中曾提到过,数据对象包含:表.视图.序列.索引和同义词.前面的笔记都是对表的想剖析,那么本次笔记就对视图的世界进行深入的剖析. 视图是通 ...

  7. MVC学习笔记---MVC生命周期及管道

    ASP.NET和ASP.NET MVC的HttpApplication请求处理管道有共同的部分和不同之处,本系列将体验ASP.NET MVC请求处理管道生命周期的19个关键环节. ①以IIS6.0为例 ...

  8. MVC学习笔记---MVC的处理管线

    漫步ASP.NET MVC的处理管线   ASP.NET MVC从诞生到现在已经好几个年头了,这个框架提供一种全新的开发模式,更符合web开发本质.你可以很好的使用以及个性化和扩展这个框架,但这需要你 ...

  9. iOS学习笔记——滚动视图(scrollView)

    滚动视图:在根视图中添加UIScrollViewDelegate协议,声明一些对象属性 @interface BoViewController : UIViewController<UIScro ...

随机推荐

  1. python中装饰器的原理以及实现,

    python版本 3.6 1.python的装饰器说白了就是闭包函数的一种应用场景,在运用的时候我们遵循 #开放封闭原则:对修改封闭,对拓展开放 2.什么是装饰器 #装饰他人的器具,本身可以是任意可调 ...

  2. [Leetcode] 2.Add Two Numbers(List To Long,模拟)

    本题题意是指将两个数倒序存储在链表中,再将两数之和同样存储在链表中输出. 我最开始的思路是将每一位相加,再考虑是否进位,但这时就需要考虑一些情况,比较麻烦. 于是我决定采取另一种在网上新学到的方法:这 ...

  3. What’s That NetScaler Reset Packet?

    What’s That NetScaler Reset Packet? https://www.citrix.com/blogs/2014/05/20/whats-that-netscaler-res ...

  4. BZOJ1031:[JSOI2007]字符加密——题解

    http://www.lydsy.com/JudgeOnline/problem.php?id=1031 喜欢钻研问题的JS同学,最近又迷上了对加密方法的思考.一天,他突然想出了一种他认为是终极的加密 ...

  5. CF527A:Playing with Paper——题解

    https://vjudge.net/problem/CodeForces-527A http://codeforces.com/problemset/problem/527/A 题目大意:一个纸长a ...

  6. 模板:数论 & 数论函数 & 莫比乌斯反演

    作为神秘奖励--?也是为了方便背. 所有的除法都是向下取整. 数论函数: \((f*g)(n)=\sum_{d|n}f(d)g(\frac{n}{d})\) \((Id*\mu)(n)=\sum_{d ...

  7. Vue推荐资料

    推荐博文(我是看过,才敢说的偶): 基础教学: 菜鸟语法教程:https://cn.vuejs.org/v2/guide/syntax.html  http://www.runoob.com/vue2 ...

  8. Object.defineProperty基本用法

    1. 基本形式 Object.defineProperty(obj,prop,descriptor) 参数说明: obj: 必需,目标对象prop: 必需,需定义或修改属性的名字descriptor: ...

  9. PHP 数据库防止攻击

    定义和用法 mysql_real_escape_string() 函数转义 SQL 语句中使用的字符串中的特殊字符. 下列字符受影响: \x00 \n \r \ ' " \x1a 如果成功, ...

  10. 获取 exception 对象的字符串形式(接口服务返回给调用者)

    工具类: package com.taotao.common.utils; import java.io.PrintWriter; import java.io.StringWriter; publi ...