MVC3 CheckboxList

时间:2012-01-17 14:58:29

标签: asp.net-mvc-3 checkboxlist

  

可能重复:
  CheckboxList in MVC3.0

您好我有两个班级的书和作者,我想要的是,当您添加一本书时,会出现一个作者列表,您可以选择其中一个或多个。最好的方法,我认为是一个清单,但没有找到一种方法来做到这一点与mvc3。但是已经阅读了一些例子并且没有理解,我只是从mvc开始,所以如果有人能告诉我怎么能做到这些我会非常感激

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;}
}

2 个答案:

答案 0 :(得分:1)

您可以向作者添加Selected布尔属性,以便了解是否为给定的书选择了他:

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

然后:

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);
    }
}

并在视图中:

@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>
}

答案 1 :(得分:0)

您需要在作者模型视图类中添加bool Selected字段(或为其创建模型视图类,以便存储此类元数据),然后它才正常像往常一样绑定:

@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>
}