2016-05-10 31 views
0

我目前正在研究MVC應用程序並將一些信息保存到數據庫中。從這個信息我保存它保存在自己的列從數據庫獲取值爲複選框的問題

string 1, string 2, string 3 

一些複選框值現在我試圖檢索這些值,使複選框在不同的頁面進行檢查。但是,我應該得到兩個複選框,我只有一個。返回的值是正確的,但對於一些奇怪的原因只有一個複選框在視圖中顯示

在我的控制,我有以下代碼

IEnumerable<MyEntity> myEntity = entityRepo.GetAll().Where(a => a.UserId == id); 
List<CheckBox> checkBoxList = new List<CheckBox>(); 
foreach (var items in myEntity) 
{ 
    checkBoxList.Add(
    new CheckBox 
    { 
     Text = items.EightWaste, 
     Checked = true, 
     Value = items.EightWaste, 
    }); 
} 

然後在視圖中我有

@foreach(var items in Model.EightWatseChkBox) 
{ 
    @Html.DisplayFor(model => items.Text) 
    @Html.CheckBoxFor(model => items.Checked) 
} 

而我的UI輸出看起來像

Output

有人可以告訴我我要去哪裏錯了嗎。

+0

什麼是myEntity.Count()的'價值;'? - 它看起來像你只有一個物品,它的'EightWaste'值是'「缺陷,運輸」' –

+0

並且作爲一個附註,你'foreach'循環不會綁定到你的模型。你需要使用'for'循環或'EditorTemplate'來輸入'CheckBox'類型 –

+0

你檢查了這個問題:http://stackoverflow.com/questions/14730746/getting-checkbox-value-in-asp-net-mvc -4? – JJP

回答

1

你的值存儲在現場爲逗號分隔字符串,因此,產生各「字」複選框,則需要分割字符串到一個數組。

MyEntity data = entityRepo.GetAll().Where(a => a.UserId == id).FirstOrDefault(); 

Model.EightWatseChkBox = data.EightWaste.Split(new char[]{ ',' }).Select(x => new CheckBox() 
{ 
    Text = x, 
    Checked = true 
}).ToList(); 

注意財產EightWatseChkBox在你的模型需要IList<CheckBox>IEnumerable<CheckBox>,這樣就可以使用for循環視圖

@for (int i = 0; i < Model.EightWatseChkBox.Count; i++) 
{ 
    @Html.DisplayFor(m => m.EightWatseChkBox[i].Text) 
    @Html.CheckBoxFor(m => m.EightWatseChkBox[i].Checked) 
} 

和POST方法,你可以加入選擇的值再次

string[] selected = model.EightWatseChkBox.Where(x => x.Checked).Select(x => x.Text); 
string combined = String.Join(",", selected); 

有關,爲什麼你不能使用更多信息環綁定到一個集合,請參閱this answer(注意:如果你不能將模型屬性更改爲IList<CheckBox>,那麼你可以使用EditorTemplate選項)

+0

我的模型屬性是'List '。感謝你,我會一起去,讓你知道我是如何得到的 – Code

+0

這工作現場!再次感謝 – Code

-1

試試這個吧,

在你的Controller裏寫如下;

IEnumerable<MyEntity> myEntity = entityRepo.GetAll().Where(a => a.UserId == id); 

ViewBag.Chekboxlist = myEntity; 

然後你的看法會

@foreach(var items in Model.EightWatseChkBox) 
{ 
     @Html.DisplayFor(model => items.Text) 
     if(ViewBag.Chekboxlist != null) 
     { 
      IEnumerable<MyEntity> myEntity = (IEnumerable<MyEntity>)ViewBag.Chekboxlist; 
      foreach(var item in myEntity) 
      { 
       @Html.CheckBoxFor(model => item.Checked) 
      } 
     } 
}