Tuesday, August 16, 2011

How to use a collection in MVC which will populate the ViewModel correctly


The view model below is a collection of strings called Images


public class PostItemViewModel
{
   public PostItemViewModel()
   {
      Images = new List<string>();
   }

   public List<string> Images { get; set; }
}


The View would look something like the code below.  The reason for the HiddenFor, is so that when  you post back to your controller, the view model that is posted back will contain the Image list.


<table>
   <tr>
   <%
   for (int i = 0; i < Model.Images.Count; i++)
   {
   %>
      <td>
         <%= Html.HiddenFor(m => m.Images[i]) %>
         <img alt="<%= Model.Images[i] %>" width="50" src="\Uploads\<%= Model.Images[i] %>" />
      </td>
   </tr>
</table>