【发布时间】:2021-06-16 08:50:13
【问题描述】:
我尝试在视图中显示来自操作的字符串。这听起来像是一项非常简单易行的任务,但我不知道如何做到这一点。
我的异步操作返回内容结果:
public async Task<IActionResult> DisplayName(string key)
{
// Retrieves the requested culture
var rqf = Request.HttpContext.Features.Get<IRequestCultureFeature>();
// Culture contains the information of the requested culture
var culture = rqf.RequestCulture.Culture;
return Content(await Task.FromResult(_displayProvider.GetDisplayName(key, culture.Name)));
}
我的视图是很简单的html:
@model List<MyModel>
<table class="table table-bordered table-striped datatable">
<thead class="table-head-dark">
<tr>
<th>
@Html.DisplayNameFor(model => model.First().Id)
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
<partial name="_EditDetailButton" model="@item.Id" />
<partial name="_DeleteButton" model="@item" />
</td>
</tr>
}
</tbody>
</table>
我想显示一个用户定义的值,而不是 @Html.DisplayNameFor(model => model.First().Id)。从 Action 返回用户定义的值。
我试过@Url.Action("DisplayName", "DisplayName", new { key = "MyModel.Id" }),但这是在渲染一个网址。
我尝试了Html.RenderAction("DisplayName", "DisplayName", new { key = "LastName" }),但 ASP.NET Core 5 中不存在 RenderAction。
我可以调用静态类 e。 G。 DisplayNameProvider.GetDisplayName("MyModel.Id", ???) 但我不知道如何让选择的文化将其传递给方法。
我如何让它工作?我也不熟悉 ASP.NET Core 中的组件。
或者是否有完全不同的显示字符串的解决方案,用户已定义并保存到数据库中? DisplayNameProvider 正在从数据库中检索字符串并处理缓存。
更新: 目标是在数据库中存储和更改属性的显示名称。用户可以更改显示名称。在我的示例中,用户希望列标题具有不同的显示名称。我不能使用资源文件,因为它们是静态的,不能在运行时更改。
这是我的 DisplayNameProvider.GetDisplayName 方法:
public string GetDisplayName(string ressourceKey, string language)
{
var ressources = GetCached(language);
var item = ressources.FirstOrDefault(r => r.ResourceKey == ressourceKey);
return item.Text;
}
提前致谢
【问题讨论】:
-
嗨@Sebastian Siemens,您对
Display a user-defined value.意味着什么?您的共享视图似乎与您的共享操作无关,或者您可能需要共享您的_displayProvider.GetDisplayName()方法。跨度> -
嗨@Rena,用户可以更改数据库中标签的值。标签在数据库中有一个键(例如
MyModel.Id)。我想在视图中显示/渲染/显示这个值。_displayProvider.GetDisplayName()只是从数据库中返回键的值。 -
嗨@Sebastian Siemens,但
@Html.DisplayNameFor用于显示键名而不显示值。 -
嗨@Rena,这就是为什么我想用我自己的操作替换
@Html.DisplayNameFor以显示不是显示名称而是来自数据库的值。来自数据库的值是用户需要作为列标题文本的值。该值就像用户想要显示为列标题的显示名称。 -
嗨@Sebastian Siemens,为什么不使用
@Html.DisplayFor?
标签: c# asp.net asp.net-core .net-core razor