5

I have a list of Key/Value pairs. basically its a List where ViewModel is a custom class of the form

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

In the View i would need to render Label and Textbox for Key and Value respectively.Im trying to use Html.DisplayFor() however it goes with model and only displays the properties of the model and not the list.

I would like to achieve something of the format

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

    <tr>

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

<% } %>

1 Answer 1

3

You could try using an editor template inside the main view which will be rendered for each item of the model (assuming your model is a collection). Editor templates are more suitable for your scenario than display templates because you are rendering text boxes which allow for editing. So it would be semantically more correct to use EditorFor rather than DisplayFor:

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

and then define an 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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.