Html.DisplayFor () in Asp.Net MVC for a list of items

I have a list of key / value pairs. basically its List, where ViewModel is a custom form class

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

In the view, I will need to display Label and Textbox for Key and Value respectively. I am trying to use Html.DisplayFor (), however it comes with a model and displays only the properties of the model, not the list.

I would like to get something in the format

  <% foreach (var item in Model) { %> <tr> <td> <%:Html.Display("item")%> </td> <td> <%:Html.Display("item.Value")%> </td> </tr> <% } %> 
+4
source share
1 answer

You can try using the editor template inside the main view, which will be displayed for each element of the model (if your model is a collection). Editor templates are more suitable for your script than display templates because you provide text fields that allow editing. Therefore, it would be semantically more correct to use EditorFor rather than DisplayFor :

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

and then define the editor template for the view model ( ~/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> 
+2
source

Source: https://habr.com/ru/post/1335365/


All Articles