2011-10-20 69 views
1

我有一个表单,在我的表单中,用户可以填写他们的详细信息并选择他们在复选框中的兴趣。作为局部视图,我将兴趣部分放置在一个表单中。如何获取mvc3表单中的复选框选定值?

具有外形,

  1. 名称
  2. 出生日期
  3. 广场
  4. 兴趣(复选框列表)

我有一个让所有领域的姓名,生日的典范,地点。 另一个模型为LookingFormodel。

现在,当我提交表格。所有的领域,如名称,生日和palce正在模型,但我没有得到复选框选定的项目列表。

如何获取表单提交中的复选框值?

+1

你能告诉我们一些代码吗? ASP.NET MVC 3完全能够将您的表单字段自动映射到模型。由于所有内容都是关于兴趣列表,请显示视图和模型的相应部分。 – Rhapsody

回答

4

这似乎是编辑器模板的好选择。与往常一样,我们开始通过设计视图模型:

public class MyViewModel 
{ 
    public string Name { get; set; } 
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] 
    public DateTime? DateOfBirth { get; set; } 
    public string Place { get; set; } 
    public IEnumerable<InterestViewModel> Interests { get; set; } 
} 

public class InterestViewModel 
{ 
    public int Id { get; set; } 
    public string InterestLabel { get; set; } 
    public bool IsSelected { get; set; } 
} 

然后控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel 
     { 
      Name = "john", 
      DateOfBirth = new DateTime(1990, 1, 1), 
      Place = "Spain", 
      Interests = new[] 
      { 
       new InterestViewModel { Id = 1, InterestLabel = "cinema" }, 
       new InterestViewModel { Id = 2, InterestLabel = "sport" }, 
       new InterestViewModel { Id = 3, InterestLabel = "books" }, 
      } 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     // TODO: process the results here, the view model will be 
     // correctly bound 
     .... 
    } 
} 

然后视图(~/Views/Home/Index.cshtml

@model MyViewModel 

@using (Html.BeginForm()) 
{ 
    <div> 
     @Html.LabelFor(x => x.Name) 
     @Html.EditorFor(x => x.Name) 
    </div> 
    <div> 
     @Html.LabelFor(x => x.DateOfBirth) 
     @Html.EditorFor(x => x.DateOfBirth) 
    </div> 
    <div> 
     @Html.LabelFor(x => x.Place) 
     @Html.EditorFor(x => x.Place) 
    </div> 
    <h2>Interests</h2> 
    @Html.EditorFor(x => x.Interests) 

    <button type="submit">OK</button> 
} 

并且将呈现相应的编辑模板为兴趣收集的每个元素(~/Views/Home/EditorTemplates/InterestViewModel.cshtml):

@model InterestViewModel 

@Html.LabelFor(x => x.IsSelected, Model.InterestLabel) 
@Html.CheckBoxFor(x => x.IsSelected) 
@Html.HiddenFor(x => x.Id) 
@Html.HiddenFor(x => x.InterestLabel) 
+0

嗨,你如何链接'InterestViewModel.cshtml'到'Index.cshtml'我完全遵循你所说的,但我刚刚只是值而不是复选框的.. ..我失踪了? – FosterZ

+0

它的工作原理如下:在视图模型中,Interests属性的类型为IEnumerable ='=> asp.net mvc将搜索文件'/ Views/Shared/EditorTemplates/InterestViewModel.cshtml',因为这是在集合中使用的类型名称。 –

+0

是的,完全谢谢你..就在一秒钟前,我搜索了关于'EditorTemplates'的信息,但我并没有意识到这一点。 – FosterZ