Kan*_*g13 11 .net c# web asp.net-core-mvc
我搜索过,但我没有找到任何方法返回一个空的IViewComponentResult.我设法做到的唯一方法是返回一个空视图.有没有更好的办法?这是我的代码:
public class ClientNavigationViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return User.IsInRole(UserRoles.CLIENT)
? View("_ClientMenu")
: (IViewComponentResult)new EmptyResult();
}
}
Run Code Online (Sandbox Code Playgroud)
这是例外:
发生了'System.InvalidCastException'类型的异常但未在用户代码中处理
附加信息:无法将"Microsoft.AspNet.Mvc.EmptyResult"类型的对象强制转换为"Microsoft.AspNet.Mvc.IViewComponentResult".
我试图返回null,但这也行不通.有任何想法吗?编辑使它像这样工作:
public class ClientNavigationViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
if (User.IsInRole(UserRoles.CLIENT))
return View("_ClientMenu");
return new EmptyViewComponent();
}
}
public class EmptyViewComponent : IViewComponentResult
{
public void Execute(ViewComponentContext context)
{
}
public Task ExecuteAsync(ViewComponentContext context)
{
return Task.FromResult(0);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 21
您可以执行以下操作:
public IViewComponentResult Invoke()
{
if (User.IsInRole(UserRoles.CLIENT))
return View("_ClientMenu");
return Content(string.Empty);
}
Run Code Online (Sandbox Code Playgroud)
小智 0
属性可以从接口继承,而不是强制转换为接口。
尝试创建一个继承自 IViewComponentResult 的对象。
public class xyz: IViewComponentResult
{
// todo
}
Run Code Online (Sandbox Code Playgroud)
然后返回这个对象。它应该有效。
| 归档时间: |
|
| 查看次数: |
2478 次 |
| 最近记录: |