Q:

HTML Helper to query database data for a given id (MVC 2 .Net C#)

I have a view that contains a list of items. I loop through those items and then I need to return another list based on the item.id from MS SQL.
What is the based way to perform this with custom HTML Helper.
<table width="100%">
 <%foreach(var item in Model.BlogList) %> 
        <%{ %>
    <tr>
        <td>
        <%: Html.ActionLink(item.title, "GetBlog", new { id = item.id, name = item.title }, null)%>
        </td>
    </tr>
    <tr>
        <td>
            <hr />
        </td>
    </tr>
    <tr>
        <td>Date: 
        <%= Convert.ToDateTime(item.createdDate).ToShortDateString() %>
        </td>
    </tr>
    <tr>
        <td>Posted By: 
        <%= item.postedBy %>
        </td>
    </tr>
    <tr>
        <td><span class='blog_post'><%= item.body %></span>
        </td>
    </tr>
     <tr>
        <td>Tags: HERE IS WHERE I need to return a new list based on item.id  (I would need a new SQL SELECT)
        </td>
    </tr>
    <%} %>
</table>

A:

I'd refactor your model so that it includes the data needed by the view.  Typically, you'd construct a view-specific model containing the data.  This model can "roll up" data from various domain models to encapsulate the data needed by the view.
For example:
public class BlogViewModel
{
    public int ID { get; set; }
    public sring Name { get; set; }
    public DateTime CreatedDate { get; set; }
    public string PostedBy { get; set; }
    public string Body { get; set; }
    public IEnumerable<TagViewMOdel> Tags { get; set; }
}

public class TagViewModel
{
    public string Tag { get; set; }
    public int ID { get; set; }
}

Then in your action (assuming you have an entity relationship between blogs and tags).
var model = this.Context
                .Blogs
                .Select( b => new BlogViewModel {
                    b.ID,
                    b.Name,
                    b.CreatedDate,
                    PostedBy = b.Author.Name,
                    b.Body,
                    Tags = b.BlogTags
                            .SelectMany( bt => bt.Tags )
                            .Select( t => new TagViewModel { t.Tag, t.ID } )
                            .ToList()
                 })
                .ToList();

Then you have all the data you need without having to involve the data context or perform another DB query.
<tr>           
    <td><% foreach (var tag in item.Tags) { %>
           <%= Html.ActionLink( tag.Tag, "tag", "search", new { id = tag.ID }, null %>
        <% } %>          
    </td>           
</tr>

