![](/img/trans.png)
[英]How to show category name instead of categoryId in view from another table in asp.net core 3.1 mvc?
[英]How to hook a view creation in ASP.NET Core 3.1 MVC and change the model and view name?
在許多操作中,我使用一個視圖模型對象來實現
public interface IResult<T>
{
Exception Error { get; }
T ViewModel { get; }
}
我只想將此對象傳遞給任何View(...)
方法,然后有一個鈎子,我可以在其中決定如何處理我的IResult
。 例如(正如我想象的那樣):
void ViewCreatingHook(SomeContext context)
{
if (context.ViewModel is IResult result)
{
if (result.Error != null)
{
context.ViewName = "Error";
context.ViewModel = new ErrorViewModel(result.Error.Message);
}
else
{
context.ViewModel = result.ViewModel;
}
}
}
是否可以?
PS 我知道我可以覆蓋Controller.View()
方法並在那里處理它,但在這種情況下,我必須覆蓋所有這些重載的方法,在我看來,它不如擁有一種全局鈎子那么健壯。
基於這個答案,我寫道:
public override ViewEngineResult FindView(ActionContext actionContext, ViewResult viewResult)
{
if (viewResult.ViewData.Model is IResult result)
{
if (result.Error != null)
{
var errorModel = new ErrorViewModel
{
Message = result.Error.Message;
};
viewResult.ViewData.Model = errorModel;
viewResult.ViewName = "Error";
}
else
{
viewResult.ViewData.Model = result.ViewModel;
}
}
return base.FindView(actionContext, viewResult);
}
並在任何其他代碼之前在ConfigureServices(IServiceCollection services)
中的Startup.cs
中注冊它:
services.TryAddSingleton<IActionResultExecutor<ViewResult>, MyViewResultExecutor>();
有用。 如果有人可以提出更好的解決方案或只是替代方案,我仍然有興趣知道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.