我有一个键/值对列表。基本上它是一个列表,其中 ViewModel 是表单的自定义类
public class ViewModel
{
public String Key { get; set; }
public String Value { get; set; }
}
在 View 中,我需要分别为键和值呈现标签和文本框。我尝试使用 Html.DisplayFor() 但是它与模型一起使用并且只显示模型的属性而不是列表。
我想实现某种格式
<% foreach (var item in Model) { %>
<tr>
<td>
<%:Html.Display("item")%>
</td>
<td>
<%:Html.Display("item.Value")%>
</td>
</tr>
<% } %>
最佳答案
您可以尝试在主 View 中使用编辑器模板,该模板将为模型的每个项目呈现(假设您的模型是一个集合)。编辑器模板比显示模板更适合您的场景,因为您正在渲染允许编辑的文本框。所以使用 EditorFor
在语义上更正确而不是 DisplayFor
:
<table>
<%= Html.EditorForModel() %>
</table>
然后为 View 模型定义一个编辑器模板(
~/Views/Home/EditorTemplates/ViewModel.ascx
):<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<YourAppName.Models.ViewModel>" %>
<tr>
<td>
<%: Model.Key %>
</td>
<td>
<%= Html.TextBoxFor(x => x.Value) %>
</td>
</tr>
关于asp.net - Asp.Net MVC 中的 Html.DisplayFor() 项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4677631/