2012-03-02 45 views
0

我有一個複選框,但形式提交打勾不被submited值...MVC複選框comeing回空

HTML:

@foreach (var radiobutton in Model.InterestedIn) 
      { 
      <span > @Html.CheckBox("selected", radiobutton) 
       <label>@radiobutton</label></span> 
       <br /> 
      } 

型號:

[Display(Name = "Would you be interested in receiving *")] 
     public IList<string> InterestedIn { get; set; } 

控制器:

IList<string> lists = new List<string>(); 
      lists.Insert(0, "Latest News"); 
      lists.Insert(1, "Special Offers"); 
      lists.Insert(1, "New Products"); 
      model.InterestedIn = lists; 

PostMethod:

[HttpPost] 
     public ActionResult Index(Competition model) 
     { 
      if (ModelState.IsValid) 
      { 
+0

控制器中的post方法是什麼樣的?它的簽名是什麼?你如何試圖訪問複選框的值? – 2012-03-02 15:35:35

回答

0

我不認爲你的代碼會編譯。 CheckBox助手期望一個布爾值作爲第二個參數,而你傳遞它一個字符串。

嘗試這樣的:

@model MyViewModel 

@using (Html.BeginForm()) 
{ 
    foreach (var value in Model.InterestedIn) 
    { 
     <span> 
      <input type="checkbox" name="interestedin" value="@Html.AttributeEncode(value)" /> 
      <label>@value</label> 
     </span> 
     <br /> 
    } 
    <button type="submit">OK</button> 
} 

這裏假設你有以下視圖模型:

public class MyViewModel 
{ 
    [Display(Name = "Would you be interested in receiving *")] 
    public IList<string> InterestedIn { get; set; } 
} 

及以下控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     IList<string> lists = new List<string>(); 
     lists.Insert(0, "Latest News"); 
     lists.Insert(1, "Special Offers"); 
     lists.Insert(1, "New Products"); 
     var model = new MyViewModel(); 
     model.InterestedIn = lists; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     return View(model); 
    } 
} 

如果你想使用CheckBox或甚至更好的CheckBoxFor幫手,你將不得不調整您的視圖模型,使其不再具有IList<string>屬性,但是IList<CheckBoxItemViewModel>屬性,其中CheckBoxItemViewModel是將包含標籤和指示是否已選擇該值的布爾屬性的另一視圖模型。

+0

對我的下拉列表中發生同樣的問題的任何幫助? – Beginner 2012-03-02 16:23:19