Search code examples
c#asp.netblazorhtml-selectmudblazor

How to add multiple dropdown list on same page in Blazor


I'm trying to insert same dropdown list multiple times in a single page.

I have an item X

I have a list of ProcessAreas (a,b,c,d,e)

I have a list of Instructions (1,2,3,4,5,6)

I need to create a form to associate to the X item a single instruction for every ProcessArea (not mandatory)

So, for example, for the item X1 I want to save to my database (a,1),(b,3),(e,6)

Indicating that for item X1 i have instructions 1 for area a, instructions 3 for area b and instruction 6 for area e. The other areas are not used.

To do this I read all instructions previously inserted in db.

I do a foreach on ProcessAreas and create a dropdown list. Inside this dropdown I put the list of available instructions, like this

@foreach (var processArea in _availableProcessAreas)
{
    var label = "Select instructions for " + processArea.ProcessAreaName;
    var x = _model.ProcessAreaInstructions.FirstOrDefault(x => x.ProcessAreaId == processArea.ProcessAreaId)?.InstructionId;

    <MudSelect T="int?" Label=@label id="@processArea.ProcessAreaId" @bind-Value="x" For="@(() => x)">
        @foreach (var instruction in _instructions)
        {
            <MudSelectItem T="int?" Value="@instruction.Id">(@instruction.Name) @instruction.Description</MudSelectItem>
        }
    </MudSelect>
} 

I can see the dropdowns on page, but I cannot select a value different from the one is displayed.

Here you can find a full sample with this strange behavior

https://try.mudblazor.com/snippet/QYGxuWFEflpORBVt

Can you help me to fix this problem and to save updated data to database?

Thanks in advance for any help.


Solution

  • By looking for the codes you add in the MudBlazor Playground, I realized that you try to bind the value of the MudSelect to your local int t = 0 razor variable.

    So I added a field in your ProcessAreaInstructionResponse, to store the value of the MudSelect.

        public class ProcessAreaInstructionResponse
        {
            public Int64 Id { get; set; }
            public string Name { get; set; }
            public int BindedValue { get; set; } = 1; // new field
        }
    
    /////
    
    <MudSelect T="int" Label=@item.Name id="@item.Id" @bind-Value="item.BindedValue">
       @foreach (var instruction in _instructions)
       {
          <MudSelectItem T="int" Value="@instruction.Id">@instruction.Description</MudSelectItem>
       }
    </MudSelect>
    

    And now it is working :)