ViewComponent的一种使用方法

最近在一个自己新建的Core项目中想使用Html.Action(),突然发现这个方法已经没了,下面我按照官网(https://docs.microsoft.com/zh-cn/aspnet/core/mvc/views/view-components?view=aspnetcore-3.1)的例子一种实现方式:

后台代码

[ViewComponent(Name = "Admin")] //指定页面调用时的名称    public class AdminViewComponent : ViewComponent    {        public async Task<IViewComponentResult> InvokeAsync(string action, object json)        {           var  objJson = json;                      Type magicType = this.GetType();            var magicConstructors = magicType.GetMethods();            var mmm = magicConstructors.FirstOrDefault(o => o.Name == action).Invoke(this, new object[] { json });            return (IViewComponentResult)mmm;        }            public IViewComponentResult ViewComponentDemo(object objJson)         {            var msg = objJson.GetType().GetProperty("msg").GetValue(objJson);            ViewBag.Msg = msg;            return View("ViewComponentDemo.cshtml");            //这里会去查找View/admin/ViewComponentDemo.cshtml具体的执行顺序可以去官网看,官网有具体的。        }    }

代码目录应该是这样才对。

前端代码(Index.cshtml)

<div class="col-md-12 graphs">@*这里调用Component的InvokeAsync方法,admin组件名称,后面为参数,这里我为了方便访问定义了一个action的方法参数*@    @await Component.InvokeAsync("Admin", new { json = new { msg = "我这里需要一个ViewComponent" }, action = "ViewComponentDemo" })    </div>

ViewComponentDemo.cshtml

<p>@ViewBag.Msg</p>

最终结果

以上就是ViewComponent的一种实现方式,自己使用起来还是较为方便的。

大佬们有好的方法,也不望赐教。

萌新刚刚开始写,若有不正确的,望指教。

有疑问的同学也可以问我,能回答的尽量回答。

(0)

相关推荐