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. iOS开发应用程序生命周期

    各个程序运行状态时代理的回调: - (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSD ...

  2. Swift中避免在多个文件中重复import相同的第三方包

    swift中由于有命名空间的存在,在同一个target创建的文件,都可以不引用直接就可以拿来使用,但是不同target之间必须要import 之后才能使用,在不同的文件中使用都要重复的import这个 ...

  3. 【Linux】- CentOS安装Mysql 5.7

    CentOS7默认数据库是mariadb,而不是mysql.CentOS7的yum源中默认是没有mysql的.所以不能使用yum install直接安装. 下载mysql的repo源 cd /usr/ ...

  4. 关于已部署的WCF服务升级的问题

    在日常的开发过程中,我们会经常迭代发布不同的版本,所以WCF服务的接口也会经常处于变动的状态,比如在传递实体类中新加一个字段.修改参数名称等等关于服务升级的问题.但是我们不可能让已发布的版本重新引用新 ...

  5. C#里面Console.Write()和Console.WriteLine()有什么区别?

    Console.Write()和Console.WriteLine()都是System.Console提供的方法,两着主要用来将输出流由指定的输出装置(默认为屏幕)显示出来.两着间的差异在Consol ...

  6. 创建udp服务端对象

    DatagramSocket ds = null;//创建服务器对象 ds = new DatagramSocket(10001);//创建对象并指定端口 byte[] bytes = new byt ...

  7. 【bzoj1212】[HNOI2004]L语言 AC自动机

    题目描述 标点符号的出现晚于文字的出现,所以以前的语言都是没有标点的.现在你要处理的就是一段没有标点的文章. 一段文章T是由若干小写字母构成.一个单词W也是由若干小写字母构成.一个字典D是若干个单词的 ...

  8. ACE线程管理机制-线程的创建与管理

    转载于:http://www.cnblogs.com/TianFang/archive/2006/12/04/581369.html 有过在不同的操作系统下用c++进行过多线程编程的朋友对那些线程处理 ...

  9. ZOJ1586:QS Network (最小生成树)

    QS Network 题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1586 Description: In th ...

  10. DOM基本代码二

    ------------------------------- <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xh ...