视图组件
asp.net core mvc 提供了部分视图的新替代品:视图组件。
视图组件与分布视图的主要区别在于视图组件与控制器不相关。可使用在独立于单个控制器的场景,如:菜单导航、侧边栏、分页栏等。
using system.threading.tasks; using microsoft.aspnetcore.mvc; public class onemodelviewcomponent : viewcomponent { //异步方式 public task<iviewcomponentresult> invokeasync(){ return task.fromresult<iviewcomponentresult>(view(new {name="rohmeng"})); } // public iviewcomponentresult invoke() // { // viewbag.msg = "视图组件"; // return view(); // } }
在shared文件夹中为视图创建components文件夹,再创建对应组件的onemodel文件夹,把需要命名为default.cshtml的视图放入其中。
shared –> components –> onemodel –> default.cshtml
<h1>@model</h1>
在其它视图中调用视图组件
@await component.invokeasync("onemodel")
或者使用 tag helper调用视图组件,要为视图组件使用tag helper需要添加@addtaghelper指令和视图组件所在的程序集名称。tag helper通过切换到小写字母来更换名称,不使用大写字母,而是添加连字符。
@addtaghelper *, 程序集名称 <div> <vc:one-model /> </div>
黄山市民网:https://www.huangshanshimin.com/