ViewComponent的一種使用方法 最近在一個自己新建的Core項目中想使用Html.Action(),突然發現這個方法已經沒了,下麵我按照官網(https://docs.microsoft.com/zh cn/aspnet/core/mvc/views/view components?vie ...
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的一種實現方式,自己使用起來還是較為方便的。
大佬們有好的方法,也不望賜教。
萌新剛剛開始寫,若有不正確的,望指教。
有疑問的同學也可以問我,能回答的儘量回答。