Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116968

How to post array of hidden values

I have a model which contains a list

public List<Property> Properties { get; set; }

In my page i read them in as hidden

 if (Model?.Client?.Properties != null)
     {
         foreach (var property in Model.Client.Properties)
         {
             @Html.HiddenFor(x => property.Id)
             @Html.HiddenFor(x => property.Value)
             @Html.HiddenFor(x => property.Key)
         }
     }

I can see in the souce on the page that they are being filled out

<input id="property_Value" name="property.Value" type="hidden" value="2018-04-17T12:14:36.1126718&#x2B;00:00" />
<input id="property_Key" name="property.Key" type="hidden" value="CreateDate" />
<input id="property_Id" name="property.Id" type="hidden" value="5" />
<input id="property_Value" name="property.Value" type="hidden" value="2018-04-17T12:14:36.1136756&#x2B;00:00" />
<input id="property_Key" name="property.Key" type="hidden" value="UpdateDate" />
<input id="property_Id" name="property.Id" type="hidden" value="6" />
<input id="property_Value" name="property.Value" type="hidden" value="21880" />
<input id="property_Key" name="property.Key" type="hidden" value="FiscalId" />

But when the form is posted the values of the other items are posted but the properties list is null. I am guessing it has something to do with the id or the name of the hiden fields.

Update:

Trying with a for loop.

for (var i = 0 ; i < Model.Client.Properties.Count() ; i++)
         {
             @Html.Hidden($"properties[{i}].id", Model.Client.Properties[i].Id)
             @Html.Hidden($"properties[{i}].value", Model.Client.Properties[i].Value)
             @Html.Hidden($"properties[{i}].key", Model.Client.Properties[i].Key)

         }

Gives

 <input id="properties_1__key" name="properties[1].key" type="hidden" value="UpdateDate" />
 <input id="properties_2__id" name="properties[2].id" type="hidden" value="6" />
 <input id="properties_2__value" name="properties[2].value" type="hidden" value="21880" />
 <input id="properties_2__key" name="properties[2].key" type="hidden" value="FiscalId" /> 

Doesnt work either

Upvotes: 2

Views: 1462

Answers (1)

DavidG
DavidG

Reputation: 118957

The problem is that your foreach loop loses the context of the property. Instead you need to use a classic for loop and index the properties. For example:

for (var i = 0 ; i < Model.Client.Properties.Count() ; i++)
{
    @Html.Hidden(x => Model.Client.Properties[i].Id)
    @Html.Hidden(x => Model.Client.Properties[i].Value)
    @Html.Hidden(x => Model.Client.Properties[i].Key)
}

Upvotes: 2

Related Questions