user3481085 user3481085 - 3 months ago 18
C# Question

DropDownListFor not changing selected value when I select a new value

I am wondering if anyone knows why my dropdownlistfor is not changing and posting back the new value to the controller when I change the option in the select list. The select list is within a forloop which shows multiple items with multiple select lists so the user can change the item they have selected to a new one.

@for (int i = 0; i < Model.PoItemsList.Count; i++)
{
net += Convert.ToDecimal(Model.PoItemsList[i].Net);
vat += Convert.ToDecimal(Model.PoItemsList[i].Vat);
gross += Convert.ToDecimal(Model.PoItemsList[i].Gross);
<tr>
<td>
@Html.HiddenFor(m => m.PoItemsList[i].Id)
@Html.HiddenFor(m => m.PoItemsList[i].NCodeId)
@Html.TextBoxFor(m => m.PoItemsList[i].ItemRef, new { @class = "form-control" })
</td>
<td>
@Html.TextBoxFor(m => m.PoItemsList[i].Description, new { @class = "form-control", @style = "width: 200px;" })
</td>
<td>
@*@Html.DropDownListFor(m => m.PoItemsList[i].NCodeId, Model.NominalCodeList, new { @class = "form-control", @id = "ncode" })*@
@Html.DropDownListFor(m => m.PoItemsList[i].NCodeId, new SelectList(Model.NominalCodeList, "Value", "Text", Model.PoItemsList[i].NCodeId), new { @class = "form-control"})
</td>
<td>
@Html.TextBoxFor(m => m.PoItemsList[i].CostPerItem, new { @class = "form-control", @Value = Convert.ToDecimal(Model.PoItemsList[i].CostPerItem) })
</td>

<td>
@Html.TextBoxFor(m => m.PoItemsList[i].Quantity, new { @class = "form-control", @style = "width: 50px;" })
</td>
<td>
@Html.TextBoxFor(m => m.PoItemsList[i].Net, new { @class = "form-control cpd-align-right", @Value = Convert.ToDecimal(Model.PoItemsList[i].Net) })
</td>
<td>
@Html.TextBoxFor(m => m.PoItemsList[i].Vat, new { @class = "form-control cpd-align-right", @Value = Convert.ToDecimal(Model.PoItemsList[i].Vat) })
</td>
<td>
@Html.TextBoxFor(m => m.PoItemsList[i].Gross, new { @class = "form-control cpd-align-right", @Value = Convert.ToDecimal(Model.PoItemsList[i].Gross) })
</td>
<td>
@Html.CheckBoxFor(m => m.ManualEntry, new {@class = "form-control"})
</td>
<td>
<input type="button" class="btn btn-danger centre" value="X" onclick="DeleteItemAndSave(@Model.PoItemsList[i].Id)" />
</td>
</tr>
}

Answer

You've got a @Html.HiddenFor(m => m.PoItemsList[i].NCodeId) and a drop down list bound to the same item; remove the hidden input and your code should work fine.