【发布时间】:2015-11-15 19:43:51
【问题描述】:
我正在尝试为数据库提取网站名称,这是模型:
public class Store
{
public int Id { get; set; }
public string StoreName { get; set; }
}
我想要做的只是对这些信息提出一个数据库请求。
这个SiteName目前在导航栏中使用,但可能会在其他地方使用。
我为导航栏创建了一个 ViewComponent:
public class NavbarViewComponent : ViewComponent
{
private IStoreRepository _storeRepository;
private string _storeName;
public NavbarViewComponent(IStoreRepository storeRepository)
{
_storeRepository = storeRepository;
_storeName = _storeRepository.GetStoreById(1).StoreName;
}
public IViewComponentResult Invoke()
{
return View((object)_storeName);
}
}
这样访问:
@model string
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" asp-controller="App" asp-action="Index">@Model</a> <!-- Here -->
...
问题是每次加载页面时都会调用数据库来获取它,这是可以理解的。但是,我不确定如何通过 one 调用存储库来访问 SiteName 并将其存储以备将来使用。
我考虑将它加载到会话变量中,但实际上它应该 100% 的时间是持久的。
【问题讨论】:
标签: asp.net-mvc entity-framework asp.net-core-mvc