Search code examples
c#asp.net-coreblazorblazor-server-side

How can I bind an HTML hidden field with a property in Blazor (server side)?


I want to bind a HTML hidden field with a property of an object. Here is my code that I'm trying to execute:

<!--ForeignKeyOptions-->
<div class="mb-3">
    <label for="foreignkeyoptions"
           class="input-group input-group-static">
        ForeignKeyOptions
    </label>
    <div class="btn-group" role="group">
        @foreach (Role? role in roleRepository
                                    .GetAll(CancellationToken.None))
        {
            <button type="button" 
                class="btn bg-gradient-primary">
                @role?.Name
            </button>
            <input type="hidden" 
                id="foreignkeyoptions"
                @bind="Test.ForeignKeyOptions" />
        }
    </div>
</div>

I tried to put the attribute value as value="role.RoleId" but Visual Studio tells me that the value attribute can't be used because @bind is using it. How can I solve this?


Solution

  • Because you have used @bind="Test.ForeignKeyOptions" in the input.
    Generally, if you want to bind the value you should use @bind-value="@role.RoleId".

    @bind is an override of @bind-value with the event set to "onchange". Which means:
    @bind=xxx"
    equals to
    @bind-value="xxx" @bind-value:event="onchange"
    So please check if you want to bind "Test.ForeignKeyOptions"or "@role.RoleId" or both.