0

我有一個CreateViewModel將複選框綁定到局部視圖列表

public class CreateViewModel 
{ 
    public AttributesViewModel AttributesInfo { get; set; } 
} 

AttributesViewModel發送到部分視圖。

public class AttributesViewModel 
{ 
    public AttributesViewModel() 
    { 
    ChosenAttributes = new List<int>(); 
    } 

    public List<Attributes> Attributes { get; set; } 
    public List<int> ChosenAttributes { get; set; } 
} 

屬性列表在局部視圖中輸出。每個人都有一個複選框。

foreach (var attribute in Model.Attributes) 
{ 
    <input type="checkbox" name="ChosenAttributes" value="@attribute.ID" /> @Attribute.Name 
} 

當我發佈CreateViewModelAttributesInfo.ChosenAttributes始終是空的,即使我查了一些箱子。我如何正確命名每個複選框,以便它綁定到ChosenAttributes列表?

我的解決方案

我把斯蒂芬·馬克的建議,做雙向綁定。所以,我創建了一個包含Value,Text和IsChecked的CheckboxInfo類。我爲它創建了一個EditorTemplate:

@model Project.CheckboxInfo 

@Html.HiddenFor(model => model.Text) 
@Html.HiddenFor(model => model.Value) 
@Html.CheckBoxFor(model => model.IsChecked)&nbsp;@Model.Text 

One GIANT警告。爲了正確地工作,我必須爲AttributesViewModel類創建一個EditorTemplate。沒有它,當發佈CreateViewModel時,它不能將複選框鏈接到AttributesInfo。

回答

1

你命名的複選框name="ChosenAttributes"CreateViewModel不包含(只有一個名爲AttributesInfo)命名ChosenAttributes的屬性。您可以讓使用

<input type="checkbox" name="AttributesInfo.ChosenAttributes" value="@attribute.ID" /> @Attribute.Name 

這項工作,但正確的做法是使用將包含一個布爾屬性(比如說)bool IsSelected和使用強類型的輔助綁定到你的財產在for循環正確的視圖模型或使用自定義EditorTemplate,以便您的控件名稱正確,並獲得雙向模型綁定。

+0

AttributesInfo.ChosenAttributes不起作用。我會嘗試雙向綁定的方式。 – ScubaSteve

+0

如果您遇到問題,很高興添加代碼,但爲什麼您的'CreateViewModel'只包含一個屬性(對於'AttributesViewModel')? - 或者它是否包含您剛剛省略的其他屬性) –

+0

是的,它包含我省略的其他屬性。這會讓我更加難以理解我的問題與不重要的屬性。 – ScubaSteve

0

我有一個類似的情況,但這是我如何做到的。解決方案並不完美,所以請原諒,如果我遺漏了一些東西,但你應該能夠聯繫。我試圖簡化你的解決方案:)

我將Attribute類名更改爲CustomerAttribute,將其重命名爲任何你喜歡的,使用單數名稱,而不是複數。添加一個屬性到你的CustomerAttribute課程中,隨心所欲地調用它,我稱之爲IsChange

public class CustomerAttribute 
{ 
    public bool IsChange { get; set; } 

    // The rest stays the same as what you have it in your Attributes class 

    public string Name { get; set; } // I'm assuming you have a name property 
} 

刪除您AttributesViewModel類,你並不真的需要它,我喜歡簡單。

修改您CreateViewModel類是這樣的:

public class CreateViewModel 
{ 
    public CreateViewModel() 
    { 
      CustomerAttributes = new List<CustomerAttribute>(); 
    } 

    public List<CustomerAttribute> CustomerAttributes { get; set; } 
} 

你的控制器會是這個樣子:

public ActionResult Create() 
{ 
    CreateViewModel model = new CreateViewModel(); 

    // Populate your customer attributes 

    return View(model); 
} 

您的文章控制器的操作方法會是這個樣子:

[HttpPost] 
public ActionResult Create(CreateViewModel model) 
{ 
    // Do whatever you need to do 
} 

在你看來,你會有這樣的事情:

<table> 
    <tbody> 

      @for (int i = 0; i < Model.CustomerAttributes.Count(); i++) 
      { 
       <tr> 
        <td>@Html.DisplayFor(x => x.CustomerAttributes[i].Name)</td> 
        <td>@Html.CheckBoxFor(x => x.CustomerAttributes[i].IsChange)</td> 
       </tr> 
      } 

    <tbody> 
</table> 

創建一個示例應用程序,並嘗試上面的代碼,看看它是否適合你。

相關問題