-2

Possible Duplicate:
CheckboxList in MVC3.0

Hi I have two classes book and author and I want is that when you add a book appears a list of authors and you can select one or more of one. the best way to do this I think is a checklist but not found a way to do this with mvc3. but have read some examples and not understood, I just starting with mvc so if someone can tell me how could I make these I would greatly appreciate

public class Book
 {
     public int IdBook {get; set;}
     public string Title {get; set;}
     public List<author> Authors  {get; set;}
 }


public class Author
{
    public int IdAuthor{get; set;}
    public string Name {get; set;}
}
Community
  • 1
  • 1
Diego_DX
  • 1,051
  • 1
  • 20
  • 33

2 Answers2

1

You could add a Selected boolean property to your Author in order to know whether he was selected for the given book or not:

public class Author
{
    public int IdAuthor { get; set; }
    public bool Selected { get; set; }
    public string Name { get; set; }
}

and then:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var book = new Book
        {
            IdBook = 1,
            Title = "foo bar",
            Authors = new[]
            {
                new Author { IdAuthor = 1, Name = "author 1" },
                new Author { IdAuthor = 2, Name = "author 2" },
                new Author { IdAuthor = 3, Name = "author 3" },
            }.ToList()
        };
        return View(book);
    }

    [HttpPost]
    public ActionResult Index(Book book)
    {
        return View(book);
    }
}

and in the view:

@model Book

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.Title)
        @Html.EditorFor(x => x.Title)
    </div>

    for (int i = 0; i < Model.Authors.Count; i++)
    {
        @Html.CheckBoxFor(x => x.Authors[i].Selected)
        @Html.LabelFor(x => x.Authors[i].Selected, Model.Authors[i].Name)    
        @Html.HiddenFor(x => x.Authors[i].Name)
    }

    <p>
        <button type="submit">OK</button>
    </p>
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

You'll need to add a bool Selected field to your author model-view class (or create a model-view class for it so you can store this kind of meta-data), and then it's just normal binding like usual:

@foreach(var book in Model.Books)
{
  <table>
    <!-- fill in the book details and create the checkbox list template -->

    @foreach(var author in book.Authors)
    {
      <tr><td>
        @Html.CheckBoxFor(x=>x.Selected);   <!-- the checkbox -->
      </td><td>
        @Html.DisplayFor(x=>x);            <!-- the description -->
                                           <!-- could also go with a nice partial view here -->
      </td></tr>
    }
  </table>
}
Blindy
  • 65,249
  • 10
  • 91
  • 131