0

I have ViewModel and Model as below

public class MyViewModel
    {  
        public List<MyModel> MyItems { get; set; }
        /* There are many other properties*/
    }

    public class MyModel
    {
        public string  MyType { get; set; }
        public decimal value1 { get; set; }
        public decimal value2 { get; set; }
    }

I am binding the razor view as below. For column 1 I can just show the string. For columns 2 and 3 I need to show text boxes with data from the model.

 <table >
    <thead>
      <tr>
        <th>My Column1</th>
        <th>My Column2</th>
        <th>My Column3</th>
      </tr>
      </thead>
        <tbody>
         @foreach (var myItem in Model.MyItems)
            {
              <tr>
                <td>
                   @myItem.MyType
                </td>
               <td>@Html.TextBoxFor( ??? )</td>
     <td></td>
              </tr>
              }
          </tbody>
 </table>

In normal cases I see that we can do like @Html.TextBoxFor(m => m.myvalue1). But how to do it in the above case. Please suggest.

San
  • 1,797
  • 7
  • 32
  • 56

2 Answers2

3

The HtmlHelpers in Razor works better by indexer. You have to do:

@for (var i = 0; i < Model.MyItems.Count; ++i)
{
    <tr>
        <td>@Model.MyItems[i]</td>
        <td>@Html.TextBoxFor(m => m.MyItems[i])</td>
        <td></td>
    </tr>
}
Simon Belanger
  • 14,752
  • 3
  • 41
  • 35
  • above works with - Html.TextBoxFor(m => m.MyItems[i]).value1 Found more details here - http://stackoverflow.com/questions/8894442/mvc-razor-view-nested-foreachs-model – San Jul 15 '13 at 05:58
1

You are already parsing your list in the @foreach loop, so you just need <td>@Html.TextBoxFor(myItem.value1)</td>

Claies
  • 22,124
  • 4
  • 53
  • 77