0

For some reason the HiddenFor helper in .NET Core (2.1.4) MVC is not setting a value on the hidden input element despite a value being present on the model property it represents.

If I manually create a hidden attribute and use IdFor, NameFor and manually set the value it works as expected.

    // This works and has a value attribute with a value
    <input type="hidden" id="@Html.IdFor(x => x.Fields[componentIndex].Value)" name="@Html.NameFor(x => x.Fields[componentIndex].Value)" value="@Model.Fields[componentIndex].Value"/>

    // This has a value attribute but it's empty
    @Html.HiddenFor(x => x.Fields[componentIndex].Value)

Note in both cases the generated names and id's are the same.

If I use a HiddenFor and provide a new { @Value=... } with the value it also doesn't set.

The only difference between the HiddenFor's that set a value (using the same code but a different component index) is that they are supplied on post and this problematic one is set in the controller.

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
neopickaze
  • 981
  • 8
  • 14
  • 1
    You need to show you controller code (most likely a `ModelState` issue - refer [TextBoxFor displaying initial value, not the value updated from code](https://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111)) –  Sep 19 '18 at 12:41
  • Share us the content of `.csproj` or a project to reproduce your issue. I made a test with `@Html.HiddenFor(x => x.Id)` under `Asp.net Core 2.1` and upgrade `Microsoft.NETCore.App` and `Microsoft.AspNetCore.App` to `2.1.4`, the result is correctly `` – Edward Sep 20 '18 at 07:57

1 Answers1

5

In ASP.NET Core you could use tag helper asp-for so the hidden will look like:

<input asp-for="ModelPropertyName" type="hidden" />

But for binding lists to POST controller actions sometimes it is easier to render hiddens explicitly (like you do) because hidden input names should follow the collection binding naming format like Fields[i].Value, where i is collection index.

For more details about collection binding check Model Binding in ASP.NET Core

Dmitry Pavlov
  • 30,789
  • 8
  • 97
  • 121