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. lintcode-185-矩阵的之字型遍历

    185-矩阵的之字型遍历 给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历. 样例 对于如下矩阵: [ [1, 2, 3, 4], [5, 6, 7, 8], [9 ...

  2. iOS开发NSDate详解

    1. 用于创建NSDate实例的类方法有 + (id)date; 返回当前时间 + (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs; 返回以 ...

  3. <Effective C++>读书摘要--Designs and Declarations<一>

    <Item 18> Make interfaces easy to use correctly and hard to use incorrectly 1.That being the c ...

  4. 访问方式由http改为https curl:(51)

    系统访问由http变为https,先申请了CA证书,然后win下浏览器访问时没问题的,但是linux下通过curl的方式访问就报错: curl:(51) SSLcertificate subject ...

  5. [转]Windows 7 蓝屏后获取 MEMORY.DMP 文件及注意事项

    转自:http://hi.baidu.com/guicomeon/item/d6753a177fc76f0f8fbde46a 系统默认会在 C:\Windows 目录下创建 MEMORY.DMP 文件 ...

  6. Linux环境PHP5.6升级7.1.8

    PHP7和HHVM比较PHP7的在真实场景的性能确实已经和HHVM相当, 在一些场景甚至超过了HHVM.HHVM的运维复杂, 是多线程模型, 这就代表着如果一个线程导致crash了, 那么整个服务就挂 ...

  7. 【EF】Entity Framework 6新特性:全局性地自定义Code First约定

    应用场景 场景一:EF Code First默认使用类名作为表名,如果我们需要给表名加个前缀,例如将类名Category映射到表Shop_Category.将Product映射到Shop_Produc ...

  8. CSS定义input disabled样式

    disabled 属性规定应该禁用 input 元素.被禁用的 input 元素既不可用,也不可点击.可以设置 disabled 属性,直到满足某些其他的条件为止(比如选择了一个复选框等等).然后,就 ...

  9. hdu 2686 Matrix && hdu 3367 Matrix Again (最大费用最大流)

    Matrix Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Subm ...

  10. CF986B Petr and Permutations

    题意翻译 Petr要打乱排列.他首先有一个从 111 到 nnn 的顺序排列,然后进行 3n3n3n 次操作,每次选两个数并交换它们. Alex也要打乱排列.他与Petr唯一的不同是他进行 7n+17 ...