zoukankan      html  css  js  c++  java
  • ViewComponent的一种使用方法

    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具体的执行顺序可以去官网看,官网有具体的。
            }
    
        }
    

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

    前端代码(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>
    

    最终结果

    image-20200330225544050

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

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

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

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

  • 相关阅读:
    C# WPF全局捕获异常 防止程序崩溃闪退
    mysql数据库动态创建分区
    mysql增加修改主键_mysql怎么修改添加主键
    C#中@的用法总结(转)
    python OpenCV使用
    turtle --- 海龟绘图¶
    Python 常用趣味模块
    Eclipse中Ant的使用
    Eclipse中Ant的使用
    Thinking in java(五)
  • 原文地址:https://www.cnblogs.com/MirLiao/p/12602059.html
Copyright © 2011-2022 走看看