![](/img/trans.png)
[英]Render an ASP.Net MVC partial view to a string when the partial view contains a render action
[英]ASP.NET Core 5 MVC Render string from action in view
我尝试在视图中显示来自操作的字符串。 这听起来像一个非常简单易行的任务,但我不明白如何做到这一点。
我的异步操作返回内容结果:
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" })
但这正在渲染 Url。
我试过Html.RenderAction("DisplayName", "DisplayName", new { key = "LastName" })
但 RenderAction 在 ASP.NET Core 5 中不存在。
我可以调用 static Class 例如DisplayNameProvider.GetDisplayName("MyModel.Id", ???)
但我不知道如何让选择的文化将其传递给方法。
我如何让这个工作? 我也不熟悉 ASP.NET 内核中的组件。
或者是否有完全不同的显示字符串的解决方案,用户已经定义并保存到数据库中? DisplayNameProvider
正在从数据库中检索字符串并处理缓存。
更新:目标是存储和更改数据库中属性的显示名称。 用户可以更改显示名称。 在我的示例中,用户希望列 header 具有不同的显示名称。 我不能使用资源文件,因为它们是 static 并且在运行时无法更改。
这是我的 DisplayNameProvider.GetDisplayName 方法:
public string GetDisplayName(string ressourceKey, string language)
{
var ressources = GetCached(language);
var item = ressources.FirstOrDefault(r => r.ResourceKey == ressourceKey);
return item.Text;
}
提前致谢
我最终使用了一个字符串本地化器,它为我的属性返回所需的值。
现在我可以使用 displaynamefor 并显示语言的值。 例如:
@Html.DisplayNameFor(model => model.MyProperty)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.