【问题标题】:Html.DisplayFor() in Asp.Net MVC for List of itemsAsp.Net MVC 中的 Html.DisplayFor() 用于项目列表
【发布时间】:2011-01-13 07:09:50
【问题描述】:

我有一个键/值对列表。基本上它是一个 List,其中 ViewModel 是表单的自定义类

public class ViewModel
{
    public String Key { get; set; }
    public String Value { get; set; }
}

在视图中,我需要分别为键和值呈现标签和文本框。我正在尝试使用 Html.DisplayFor() 但是它与模型一起使用并且只显示模型的属性而不是列表。

我想实现某种格式的东西

 <% foreach (var item in Model) { %>

    <tr>

        <td>
            <%:Html.Display("item")%>
        </td>
     <td>
            <%:Html.Display("item.Value")%>
        </td>
    </tr>

<% } %>

【问题讨论】:

    标签: asp.net asp.net-mvc-2


    【解决方案1】:

    您可以尝试在主视图中使用编辑器模板,该模板将为模型的每个项目呈现(假设您的模型是一个集合)。编辑器模板比显示模板更适合您的场景,因为您正在呈现允许编辑的文本框。所以使用EditorFor而不是DisplayFor在语义上更正确:

    <table>
        <%= Html.EditorForModel() %>
    </table>
    

    然后为视图模型定义一个编辑器模板(~/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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多