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. nginx 设置默认虚拟 host

    nginx 设置默认虚拟 host listren 80 default_server

  2. ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction 表被锁的解决办法

    转自:https://blog.csdn.net/mchdba/article/details/38313881 前言:朋友咨询我说执行简单的update语句失效,症状如下:mysql> upd ...

  3. 如何在存储过程中执行set命令  我来答

    1.EXEC使用EXEC命令两种用种执行存储程另种执行态批处理所讲都第二种用 面先使用EXEC演示例,代码1DECLARE @TableName VARCHAR(50),@Sql NVARCHAR ( ...

  4. lambda 分组练习

    public partial class Form1 : Form { public Form1() { InitializeComponent(); } List<Person> per ...

  5. 在上传文件时候 request.setCharset对文件名有效 对普通文本域无效 需要通过手动转换编码方式编码

    在上传文件时候 request.setCharset对文件名有效 对普通文本域无效 需要通过手动转换编码方式编码

  6. java 写入int型时会自动转换成字符

    java  写入int型时会自动转换成字符

  7. Properties 的list方法 直接将内容放到文本中

    Properties 的list方法 直接将内容放到文本中

  8. 2011 Multi-University Training Contest 8 - Host by HUST

    Rank:56/147. 开场看B,是个线段树区间合并,花了2hour敲完代码...再花了30min查错..发现push_down有问题.改了就AC了. 然后发现A过了很多人.推了个公式,发现是个分段 ...

  9. Dom事件的三种绑定方式

    1.事件 2.  onclick, onblur, onfocus, 需求:请写出一个行为,样式,结构,相分离的页面.   JS,   CSS,  HTML, 示例1,行为结构样式粘到一起的页面: & ...

  10. 【题解】Atcoder ARC#67 F-Yakiniku Restaurants

    觉得我的解法好简单,好优美啊QAQ 首先想想暴力怎么办.暴力的话,我们就枚举左右端点,然后显然每张购物券都取最大的值.这样的复杂度是 \(O(n ^{2} m)\) 的.但是这样明显能够感觉到我们重复 ...