【问题标题】:MVC3 CheckboxList [duplicate]MVC3 CheckboxList [重复]
【发布时间】:2012-01-17 14:58:29
【问题描述】:

可能重复:
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;}
}

【问题讨论】:

标签: asp.net-mvc-3 checkboxlist


【解决方案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>
}

【讨论】:

    【解决方案2】:

    您需要将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>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      相关资源
      最近更新 更多