ASP.NET MVC strongly typed model binding to a collection with zero values.

I wasn’t quite clear how to do this and I’m not sure my solution is the best approach, but it certainly falls within the realm of normal functionality included in ASP.NET MVC.

The page I wanted to have was a partial view that listed out comments associated with a particular model object. So, if someone posted a comment on a particular Project object then I wanted to pass the object type and value to the partial view and have it render all the comments associated with that that object’s value.

So One Project has Many Comments.

The Comment partial view was to show the list of comments and then if the user was logged in it would also display a comment box for them to submit a new comment.

I wanted to bind the comment box fields to the model so that my DataAnnotations would show up properly. The only problem is that if you have a collection bound to your view it isn’t particularly straightforward binding only one set of values to your input fields. It’s quite easy to iterate over fields in your collection and use strongly typed helper methods to render each item, but if you only want one set of fields it becomes onerous.

Here is the solution I came up with (which is probably obvious to some, but for some reason I couldn’t find this when searching).

@model IEnumerable<Comment>

@if (Model != null)
    {
        foreach (var item in Model)
        {
            <div>Posted On: @item.DateCreated</div>
            <div>Last Updated On: @item.DateModified</div>
            <div>Subject: @item.Title</div>
            <div>Comment: @item.CommentText</div>     
            <div>Posted By: @item.UserInfo.UserName</div>
            <div>------</div>
        }
    }
        
    Html.RenderPartial("CommentSubmit", (IEnumerable<Model.Comment>)ViewBag.Comments, new ViewDataDictionary() { new KeyValuePair<string, object>("objid", objectid), new KeyValuePair<string, object>("objtype", objecttype) });

This is the main page, where the collection is rendered out and then at the bottom we call the helper method Html.RenderPartial, which in this case is actually pretty helpful in that you can pass

Leave a Reply

Your email address will not be published. Required fields are marked *