views:

348

answers:

2

I have two tables, Author and Book, where an author can have many books. I've got an edit view set up as "System.Web.Mvc.ViewPage(of MyDatabase.Author)". The form is set up to show the Author and all his books, with the ability to edit book information:

<% Using Html.BeginForm()%>
<%=Model.author_name%> <br/>
<% For Each item In Model.Books%>
<%=Html.CheckBox("checked_out")%>
<%=item.book_name%> <br/>
<% Next%>
<input type="submit" value="Save" />
<% End Using%>

In the controller, I've got the Post function:

<ActionName("Edit"), AcceptVerbs(HttpVerbs.Post)> _
Function Save(ByVal form As Author) As ActionResult
   Dim book_count = Author.Books.Count
End Function

The problem is that the Books collection isn't part of the post - book_count is zero, even though there are several books displayed.

Am I doing something wrong, or am I expecting too much in the post? How can I make this work?

+1  A: 

I believe your problem is that the "magic parser" for MVC has nothing to hang it's hat on. When you put items on your page that you want to be able to grab back on the post that are enumerated inside of a collection, you've got to give your "things" names. So, what I did in my page is if I didn't want them to be able to edit a field, like your book name above, I would use a hidden field to wrap the value up in a control that MVC can get at via magic and then also display that value to the user. So, it could look something like:

<% for (i = 0; i < Model.Books.Count; i++) {
       book = Model.Books[i] as book //I'm a C# guy so make this VB
<%= Html.CheckBox("author["+1+"].checked_out", book.checked_out) %>
<%= HtmlHidden("author["+i+"].book_name",book.book_name) %>
<%= book.book_name %>
<% } %>

...and then this should come back all nicely packaged for you as a book collection in your Authors object. See if that gets you in the right direction.

EDIT One other thought too. I'm using the UpdateModel method to fetch the results. It shouldn't matter, but I thought I'd throw that in there.

Nick DeVore
I'm a little confused. Shouldn't the hidden value be "books["+i+"]..." or "author.book["+i+"]..." or something? Also, I'm assuming "book" at the beginning of line 2 should be "item".
gfrizzle
Also, why doesn't "checked_out" need the same kind of control naming as "book_name"?
gfrizzle
Yep, you're right. Let me clean up the code a bit here.
Nick DeVore
A: 

See here for the full answer to this problem. I basically didn't grok how MVC wanted the variables to be named.

gfrizzle