2011-10-20 119 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