ASP NET MVC 4 collection is null on post

后端 未结 3 770
时光取名叫无心
时光取名叫无心 2020-12-22 13:06

I read most of Google :-), but I can\'t proceed. The collection on my object is and stays null on post, whatever I do.

My Model:

public class Artic         


        
3条回答
  •  隐瞒了意图╮
    2020-12-22 13:51

    Collection indexers must start at zero and be consecutive (unless you include an Index property).Because of your if statements, you are not necessarily generating a control for the property Anzahl. Looking at your header information, you do not have a value for ArtikelListe[0].Anzahl which means that the first item must have either IstKategorie=true or MitAnzahl=false. You can correct this by adding a hidden input so a value posts back

    @if (Model.ArtikelListe[i].IstKategorie)
    {
      @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)
    @Html.LabelFor(x => x.ArtikelListe[i].Information) @Html.HiddenFor(x => x.ArtikelListe[i].Anzahl) // add this } else { if (Model.ArtikelListe[i].MitAnzahl) { @Html.TextBoxFor(x => x.ArtikelListe[i].Anzahl, new { @class = "field text fn" }) } else { @Html.LabelFor(x => x.ArtikelListe[i].Anzahl) @Html.HiddenFor(x => x.ArtikelListe[i].Anzahl) // add this } @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)
    @Html.LabelFor(x => x.ArtikelListe[i].Information) }

    Alternatively you can add an Index property which the DefaultModelBinder uses to match up collection items that are non-consecutive

    @if (Model.ArtikelListe[i].IstKategorie)
    {
      @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)
    @Html.LabelFor(x => x.ArtikelListe[i].Information) } else { if (Model.ArtikelListe[i].MitAnzahl) { @Html.TextBoxFor(x => x.ArtikelListe[i].Anzahl, new { @class = "field text fn" }) // add this manually } else { @Html.LabelFor(x => x.ArtikelListe[i].Anzahl) } @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)
    @Html.LabelFor(x => x.ArtikelListe[i].Information) }

    With the first option, it will post back all items. In the second case it will post back only items that meet the if conditions.

    Note as Sergey noted, you need to also remove

提交回复
热议问题