Primary key set to zero on submit of IEnumerable

2019-08-29 01:22发布

问题:

So I created a variable length list using the code shown here.

When I submit the form, the primary keys are reset to 0. In the HTML form, they are not zero but the actual values. How do I fix this?

The form

@using (Html.BeginCollectionItem("Kortingartikel")) { 

    @Html.HiddenFor(x => x.Artikelid)
    @Html.TextBoxFor(x => x.Artikelnaam)
    @Html.TextBoxFor(x => x.Prijs)</td>

}

The data

According to Chrome, this data is sent to the server:

Kortingartikel.index:ad56efb0-ab7f-4b37-9d9b-712d7c3e3543
Kortingartikel[ad56efb0-ab7f-4b37-9d9b-712d7c3e3543].Artikelid:5
Kortingartikel[ad56efb0-ab7f-4b37-9d9b-712d7c3e3543].Artikelnaam:test artikel een
Kortingartikel[ad56efb0-ab7f-4b37-9d9b-712d7c3e3543].Prijs:10,00
Kortingartikel.index:b9624d8f-38e6-4092-ba1b-d004d0443a43
Kortingartikel[b9624d8f-38e6-4092-ba1b-d004d0443a43].Artikelid:6
Kortingartikel[b9624d8f-38e6-4092-ba1b-d004d0443a43].Artikelnaam:test artikel twee
Kortingartikel[b9624d8f-38e6-4092-ba1b-d004d0443a43].Prijs:5,00

The Action

The data is sent to the following action:

public ActionResult Kortingartikel(IEnumerable<Kortingartikel> Kortingartikel)

The 'Kortingartikel' parameter has the following values:

[0]Artikelnaam:test artikel een
   Prijs: 10
   Artikelid: 0
[1]Artikelnaam:test artikel twee
   Prijs: 5
   Artikelid: 0

The property/field Artikelid Artikelid is generated from a linq-to-sql dbml file. Here is the (autogenerated) code:

[global::System.Data.Linq.Mapping.ColumnAttribute(Name="artikelid", Storage="_artikelid", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]
    public long Artikelid
    {
        get
        {
            return this._artikelid;
        }
                    set
        {
            if ((this._artikelid != value))
            {
                this.OnArtikelidChanging(value);
                this.SendPropertyChanging();
                this._artikelid = value;
                this.SendPropertyChanged("Artikelid");
                this.OnArtikelidChanged();
            }
        }
    }

回答1:

I suspect that the Artikelid on your Kortingartikel view model either doesn't have a setter:

public int Artikelid { get; } // Bad

or it isn't public:

protected int Artikelid { get; set; } // Bad

or it isn't a property at all but it is a field:

public int Artikelid; // Bad

In all those cases the default model binder wan't be able to set its value from the request. So make sure that this property is declared with public getter and setter on your view model:

public int Artikelid { get; set; } // Good

Also to avoid possible conflicts try renaming your action parameter:

public ActionResult Kortingartikel(IEnumerable<Kortingartikel> model)