views:

454

answers:

0

I'm using the L2S designer to generate classes from my DB. The app is your average blog kind of thing. I have a many to many relationship between Posts and Topics with a table PostsTopics that links them.

When editing a post I'd like to display a checkbox for each topic and pre-check the ones for which there are values in the PostsTopics table for that post. Pretty standard stuff.

Things I've tried:

<%= Html.HiddenFor(x => x.Post.PostId) %>
<%= Html.HiddenFor(x => x.Post.CreateUserId) %>

<%= Html.LabelFor(x => x.Post.Title) %>
<%= Html.EditorFor(x => x.Post.Title) %>&nbsp;
<%= Html.ValidationMessageFor(x => x.Post.Title) %>

...

<% for (int i = 0; i < Model.Post.PostsTopics.Count; i++)
{ %>
    <input type="hidden" value="Post.PostsTopics[<%= i %>].TopicId" />
    <input type="checkbox" name="Post.PostsTopics[<%= i %>].Topic" value="<%= Model.Post.PostsTopics[i].Topic.TopicId %>" /><%= Model.Post.PostsTopics[i].Topic.Desc%>
    <input type="hidden" value="Post.PostsTopics[<%= i %>].PostId" />
<% } %>  

I tried to use the default model binder here to just pick up he Post.PostsTopics EntitySet from the form POST without luck. I've tried variations on this theme without luck, indicating that I don't really know what's going on with the model binder. I've also tried the Html.CheckboxFor extension but it doesn't seem to work like others, not sure what's going on there, keep getting compiler errors. So aside from accepting a FormCollection param and looping/pulling out data manually what is the best way to accomplish this? This seems like it should be a "solved problem" as Jeff likes to say but I haven't found any definitive How To guides or anything online.

My question is two fold. I'd like to know the best way to package and render the list of checkboxes with the appropriate ones pre-checked. I'm using a view model class so I can perform this in the controller, view model, or view itself (I personally think the view model is the right place for this task but am open to suggestions). I also want the checked checkboxes returned to my HttpPost action method. Right now I'm taking a strongly typed Post object in as the action method parameter. I can think of ugly ways to accomplish this involving nested loops but there's got to be a better, more elegant way.