title: Loading many to many data into viewmodel in mvc entity framework
body: <p>View Model</p>
  
  <pre><code>public class ItemDetail
  {
      public IEnumerable&lt;DescriptionTag&gt; DescrptionsTags { get; set; } //many to many join table
      public IEnumerable&lt;Item&gt; Items { get; set; }
  }
  </code></pre>
  
  <p>Controller action</p>
  
  <pre><code>public ActionResult Index(int? id)
      {
          ItemDetail viewModel=new ItemDetail();
  
          viewModel.Items = db.Items.Include(i=&gt;i.DescriptionTags); //eager loading related data
  
          if (id != null)
          {
              viewModel.DescrptionsTags = viewModel.Items.Where(i =&gt; i.ID == id.Value).Single().DescriptionTags; // loads the description tags to viewmodel property
          }
  
  
          return View(viewModel);
      }
  </code></pre>
  
  <p>View</p>
  
  <pre><code>@foreach (var item in Model.Items) {
  
  &lt;tr&gt;
      &lt;td&gt;
          @Html.DisplayFor(modelItem=&gt;item.ID)
      &lt;/td&gt;
      &lt;td&gt;
          @*Loading tags in the table*@
          @if (Model.DescrptionsTags != null)
          {
              foreach (var tag in item.DescriptionTags)
              {
                  &lt;a&gt;@tag.Description.DescriptionName&lt;/a&gt;
              }
          }
      &lt;/td&gt;
      &lt;td&gt;
          @Html.DisplayFor(modelItem =&gt; item.Size)
      &lt;/td&gt;  
      &lt;td&gt;
          @Html.ActionLink("Select", "Index", new { id=item.ID}) |
          @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
          @Html.ActionLink("Details", "Details", new { id=item.ID }) |
          @Html.ActionLink("Delete", "Delete", new { id=item.ID })
      &lt;/td&gt;
  &lt;/tr&gt;
  }
  </code></pre>
  
  <p>Details:</p>
  
  <p>The code works fine. The problem is, the tags do not get loaded into table until the user clicks the select link or when the page is loaded for the first time. Which is, the table gets loaded with tags only when an id is passed to the controller. That is not how I want it to behave. Is there a way I can load the tags without needing to pass the id?</p>
  
  <p>What I am trying to do is similar to the tags in Stackoverflow. Each post has many tags and each tags can have many posts. What I need is, in a table column I want to load all the tags that relate to the particular item id of the row.</p>
  
  <p>I am currently following a tutorial from this link - <a href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application" rel="nofollow">http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application</a> .
  But the above code is my own version based on the tutorial. So, there might be a completely different way of doing what I am trying.</p>