Visual
一句话的事儿
- 根据不同的条件,页面渲染的结果不同,比如用户处于登录状态那么显示Logout,相反则显示Register
- 就是页面的一些插件,比如手机页面的网络状况呀,全局使用
条件 Tag Helpers
ConditionTagHelper:
[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();
}
}
使用 ConditionTagHelper:
<li class="nav-item" condition="SignInManager.IsSignedIn(User)">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</a>
</li>
<li class="nav-item" condition="SignInManager.IsSignedIn(User)">
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
<button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
<li class="nav-item" condition="!SignInManager.IsSignedIn(User)">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
</li>
<li class="nav-item" condition="!SignInManager.IsSignedIn(User)">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
Tag Helpers 前缀
通过 Tag Helpers 前缀避免名称冲突。
以 “my:” 作为 Tag Helpers 前缀:
@tagHelperPrefix "my:"
...
<ul class="navbar-nav">
<li class="nav-item" condition="SignInManager.IsSignedIn(User)">
<my:a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</my:a>
</li>
<my:li class="nav-item" condition="SignInManager.IsSignedIn(User)">
<my:form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
<button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</my:form>
</my:li>
...
</ul>
View Component
- 显示部分内容
- Mini Controller
- 可复用
- 只能配合父级 View 使用
建立 View Component:
- 继承 ViewComponent 父类
- 实现 Invoke() 方法
- 返回 IViewComponentResult
- 或实现 InvokeAsync() 方法
- 返回 Task
- 返回 Task
View Component 实例
InternetStatus:
public class InternetStatus : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://www.baidu.com");
return View(response.StatusCode == HttpStatusCode.OK);
}
}
View Component 的 View:
@model bool
@if (Model)
{
<span class="badge badge-success">Connected</span>
}
else
{
<span class="badge badge-danger">Not Connected</span>
}
在 _Layout 中进行使用:
<div class="container">
<partial name="_CookieConsentPartial" />
<main role="main" class="pb-3">
@RenderBody()
@await Component.InvokeAsync("InternetStatus")
</main>
</div>
注:View Component 只有放在 Shared 目录下才能全局可用。