2017-08-26 48 views
0

我生成的局部視圖模型的foreach元素名稱產生不正確

@model IEnumerable<ViewModel.vm_Master_QuestionSet_AnswerOptions> 

    @foreach (var item in Model) 
    { 
     <div class="form-group"> 
      @Html.LabelFor(m => item.AnswerShownOrder, item.AnswerShownOrder.ToString(), new { @class = "control-label col-md-3 col-sm-3 col-xs-12" }) 
      <div class="col-md-4 col-sm-4 col-xs-4"> 
       @Html.TextBoxFor(m => item.AnswerOptionText, new { @class = "form-control", @id = item.PK_MasterQuestion_AnswerOptionID }) 


      </div> 
      <div class="col-md-2 col-sm-2 col-xs-2"> 

       @Html.CheckBoxFor(m => item.CorrectAnswer, new { @class = "form-control", @id = "chk" + item.PK_MasterQuestion_AnswerOptionID }) 

      </div> 
     </div> 
    } 

當但創建控件的名稱開始與item.please看到波紋管圖像 enter image description here 在I類有2個屬性

public ICollection<string> AnswerOptionText { get; set; } 
     public ICollection<bool> CorrectAnswer { get; set; } 

如果名字是這樣生成的,則值不會映射。

爲什麼它會生成這樣的?我如何防止這種情況?

回答

0

在你的模型類使用下面的代碼:

[System.ComponentModel.DataAnnotations.Display(Name = "Whatever name you want to assign to it")] 
public ICollection<string> AnswerOptionText { get; set; } 
0

要映射這仍然是字符串的集合的屬性。你需要另一個for循環之前,你可以看到顯示:

@model IEnumerable<ViewModel.vm_Master_QuestionSet_AnswerOptions> 

@foreach (var item in Model) 
{ 
    <div class="form-group"> 
     @Html.LabelFor(m => item.AnswerShownOrder, item.AnswerShownOrder.ToString(), new { @class = "control-label col-md-3 col-sm-3 col-xs-12" }) 

    @foreach (var itemAnswer in item.AnswerOptionText) 
    { 
     <div class="col-md-4 col-sm-4 col-xs-4"> 
      @Html.TextBoxFor(c => itemAnswer, new { @class = "form-control", @id = item.PK_MasterQuestion_AnswerOptionID }) 
     </div> 
    } 
} 

你需要做的for循環以及對ICollection CorrectAnswer財產。最後,擁有一組屬性集合的模型並不是一個好主意。要麼你宣佈一個模型,您CSHTML觀點與不同的集合像這樣的:

@model vm_Master_QuestionSet_AnswerOptions 

與連接到它的屬性集合:

public ICollection<string> AnswerOptionText { get; set; } 
public ICollection<bool> CorrectAnswer { get; set; } 

並沒有這一項是很難,特別是如果它保持包含屬性集合:

@model IEnumerable<ViewModel.vm_Master_QuestionSet_AnswerOptions>