1.HtmlHelper扩展方法:
public static class HtmlHelperEx
{
public static IHtmlContent Br(this IHtmlHelper helper)
{
return new HtmlString("</Br>");
}
}
在cshtml中使用@Html.Br();
2.TagHelper组件:
[HtmlTargetElement("Hello")]
public class TagHelperTest:TagHelper
{
public string Name { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div";
if(!string.IsNullOrEmpty(Name))
output.Attributes.Add("name", Name);
output.PreContent.SetContent("");
}
}
接着在_ViewImports.cshtml中注入,@addTagHelper *, WebApplicationStudy(@addTagHelper 组件名字,项目名字),其中*表示所有;在cshtml中使用<Hello Name="hello"></Hello>;
3. 局部视图,@Html.Partial("视图名字"),第二个参数可以使用model传值,@Html.Partial("视图名字",@model)
4.视图组件
(1)创建类,以ViewComponent结尾,继承ViewComponent类,如下:
[ViewComponent(Name="CustomList")]
public class ListViewComponent:ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string name)
{
var result = await GetListPerson(name);
return View(result);
}
private Task<List<Person>> GetListPerson(string name)
{
return Task.Run(() =>
{
return new List<Person>
{
new Person
{
Id=1,
Name = name+1,
},
new Person
{
Id=2,
Name = name+2,
},
new Person
{
Id=3,
Name = name+3,
},
new Person
{
Id=4,
Name = name+4,
},
};
});
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
如果?[ViewComponent(Name="CustomList")]没有指定,默认是类名除去ViewComponent部分;
(2)创建文件Shared/Components/CustomListDefault.cshtml,因为return View(result)默认找的地址,如果不默认,可以指定,例如:return View("~/Views/Test/Test.cshtml",result);
Shared/Components/CustomListDefault.cshtml代码如下:
@using WebApplicationStudy.Common
@model List<Person>
@foreach(var item in Model)
{
<p id="@item.Id">@item.Name</p>
}
(3)最后在其它cshtml中使用:
@await Component.InvokeAsync("CustomList",new { name="123kk" })
|