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. 第四章 持续集成jenkins工具使用之项目配置

    1.1   创建项目 点击“新建”,输入项目名称,选择“构建一个自由风格的软件项目”,点击ok,项目创建完成. 1.2   配置项目 点击步骤1创建的项目,进入项目页面,如图: 点击“配置”,进入配置 ...

  2. BZOJ 1787 紧急集合(LCA)

    转换成抽象模型,就是要求一棵树(N个点,有N-1条边表示这个图是棵树)中某一点满足给定三点a,b,c到某一点的距离和最小.那么我们想到最近公共祖先的定义,推出只有集合点在LCA(a,b).LCA(a, ...

  3. linux系统环境代理设置

    系统上网代理设置: 1.编辑文件/etc/profile,增加如下两行 export http_proxy=http://ip:port export https_proxy=http://ip:po ...

  4. [洛谷P2161][SHOI2009]会场预约

    题目大意:有两种操作: $A\;l\;r:$表示加入区间$[l,r]$,并把与之冲突的区间删除,输出删除的区间的个数,区间$A$于区间$B$冲突当且仅当$A\cap B\not=\varnothing ...

  5. [洛谷P2408]不同子串个数

    题目大意:给你一个字符串,求其中本质不同的字串的个数 题解:同[洛谷P4070][SDOI2016]生成魔咒,只要最后再输出就行了 卡点:无 C++ Code: #include <cstdio ...

  6. Html CSS学习(五)position定位 原

    Html CSS学习(五)position定位 position用来对元素进行定位,其值有以下几种: static:无特殊定位,对象遵循正常文档流,top,right,bottom,left等属性不会 ...

  7. 洛谷 P3119 [USACO15JAN]草鉴定Grass Cownoisseur 解题报告

    P3119 [USACO15JAN]草鉴定Grass Cownoisseur 题目描述 约翰有\(n\)块草场,编号1到\(n\),这些草场由若干条单行道相连.奶牛贝西是美味牧草的鉴赏家,她想到达尽可 ...

  8. 项目管理---git----快速使用git笔记(三)------coding.net注册和新建项目(远程仓库)

    我们在第一章已经了解了github和coding.net的区别: github是一个基于git的代码托管平台,付费用户可以建私人仓库,我们一般的免费用户只能使用公共仓库,也就是代码要公开. codin ...

  9. NOIP2016Day2T3愤怒的小鸟(状压dp) O(2^n*n^2)再优化

    看这范围都知道是状压吧... 题目大意就不说了嘿嘿嘿 网上流传的写法复杂度大都是O(2^n*n^2),这个复杂度虽然官方数据可以过,但是在洛谷上会TLE[百度搜出来前几个博客的代码交上去都TLE了], ...

  10. php 在线预览word

    一般类似oa或者crm等管理系统可能都会遇到需要再线查看word文档的功能,类似百度文库. 记得去年小组中的一个成员负责的项目就需要这个的功能,后面说是实现比较困难,就将就着用chm格式替代了.今天看 ...