Search code examples
c#asp.net-coreasp.net-core-2.0tag-helpersasp.net-core-tag-helpers

tag helper [asp-for] for the input doesn't work with byte's array values (opposite to @Html.HiddenFor)


When @Html.HiddenFor(e=>e.RowVersion) works well and generates:

<input id="RowVersion" name="RowVersion" type="hidden" value="AAAAAAAARlI=" /> 

But the tag helper version <input asp-for="@Model.RowVersion" name="RowVersion" hidden /> generates:

<input name="RowVersion" hidden id="RowVersion" value="System.Byte[]" />

Problem there is crazy value "System.Byte[]".

I want to keep using tag helper version for consistency. How I can enable bytes array serialization?


Solution

  • Use type="hidden" instead of hidden attribute!

    You should be able to achieve the same thing if you do

    /*
     *   From the ViewModel:
     *       byte[] RowVersion = Encoding.UTF8.GetBytes("FR")
     */
    <input asp-for="RowVersion" type="hidden" />
    

    Comparison

    enter image description here enter image description here

    The reason (I am not 100% sure though)

    Tag helper asp-for will try to generate the type for the HTML input based on the property type the tag helper binds to, when you don't specify a type attribute on the HTML input. If it can't find a proper type for the HTML input, it would default to type="text".

    That's why your <input asp-for="RowVersion" hidden /> will generate a hidden textbox. Tag helper doesn't sanitize the input value when generating textbox:

    enter image description here

    But if you specify type="hidden" and your property type is byte[], it will actually do the Base64 encoding for you:

    enter image description here

    That's why @Html.HiddenFor() as well as <input type="hidden" asp-for= /> worked but the others didn't!