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的一種實現方式,自己使用起來還是較為方便的。

大佬們有好的方法,也不望賜教。

萌新剛剛開始寫,若有不正確的,望指教。

有疑問的同學也可以問我,能回答的盡量回答。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM