johnnycakes
johnnycakes

Reputation: 2450

ASP.NET MVC newbie: getting/passing data in dropdown form for multiple objects in an edit View

Using the Authors/Books catalog example, let's say I want to edit the info for the books of a specific author.

When someone navigates to domain.com/Books/Edit/2, I want to display an edit view for all the books where Author_ID = 2. Among the various book info is the book category (fiction, non-fiction, textbook, whatever) These categories are in their own table and are referenced by a Category_ID.

What's the best way to set up the edit form?

Currently in my controller I have something like this:

public ActionResult Edit(int id)
        {

            IQueryable<Book> books =  bookRepository.FindBooksForAuthor(id);
            return View(books);
        }

And in my partial view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IQueryable<Authors.Models.Book>>" %>

    <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

    <% using (Html.BeginForm()) {%>

        <fieldset>
            <legend>Fields</legend>
            <%var i = 0;
              foreach (var book in Model)
              {%>



            <p>
                <label for="Category_ID">Category_ID:</label>
                <%= Html.TextBox("Category_ID", book.Category_ID)%>
                <%= Html.ValidationMessage("Category_ID", "*")%>
            </p>
            <p>
                <label for="Description">Description:</label>
                <%= Html.TextBox("Description", book.Description)%>
                <%= Html.ValidationMessage("Description", "*")%>
            </p>

            <%i++;
              } %>
               <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>

    <% } %>

Is my Inherits set properly at the top of the view since I'm passing an IQueryable object?

More importantly, how do I get the Category_ID field to be a DropDown with the correct category selected? Can I just send the data for the dropdown to the view and figure out the selected item at the view level?

ViewData["categories"] = new SelectList(_db.BookCategories.ToList().OrderBy(b => b.Category_Title), "Category_ID", "Category_Title");

Upvotes: 2

Views: 1546

Answers (1)

LukLed
LukLed

Reputation: 31842

You could create view model class containing list of books and select list of categories:

public class BooksEditViewModel 
{
    public IQueryable<Authors.Models.Book> Books { get; set; }
    public IQueryable<BookCategory> BookCategories { get; set; }
}

Then use BooksEditViewModel as view model

System.Web.Mvc.ViewUserControl<BooksEditViewModel>

and code dropdown with

Html.DropDownList("Category_ID", new SelectList(Model.BookCategories,"Category_ID", "Category_Title",book.Category_ID);

You should also read about list binding:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Upvotes: 0

Related Questions