Blazor - Create select box dynamically

I'm translating an old JavaScript/JQuery application into Blazor and one of the last things I need to figure out is how to add a select dropdown, with options, dynamically onto the UI.

In the old JavaScript program, I did this by making a "+" clickable:

<span class="add"><span class="add2"> + </span>

When clicked, it called an .on("click") which just rendered the html with a .insertAfter and the select box appeared dynamically after the previous element (which also happened to be a select box). The count > 2 towards the bottom kept more than 2 selects from getting added:

$('.add').on('click', function(){
    var everything = "<select name='number" + (count + 1) + "' class='number" + (count + 1) + "'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option></select>'";
    $(everything).insertAfter('.number' + count).addClass('add2');
    count +=1;
    if(count > 2){
    $('.add').remove();
    }
});

In Blazor, it looks like there are some ways to do this without JavaScript, which I guess is the entire point of Blazor, such as "RenderFragment" with methods such as ".AddContent" and ".AddAttribute," etc. I haven't yet found enough documentation on this technique to know if it's the way to go. Is this the way Blazor plans on adding/removing elements from the UI? Am I on the right path? Or very cold, oh so cold? I'd like to do this in the most recent recommended Blazor way.

Any suggestions, directions or documentation would be appreciated!

Answers:

Answer

You do not need to use any RenderFragment() method directly. Just create a plain simple Blazor component that will have:

  • a view model to hold the "description" of the state of your dynamic form
  • the corresponding logic that will convert the view model to HTML

Something like the following will do the work; see the inline comments for explanation:

@page "/Test"


@*Render the button if current number of select boxes is less than 2*@
@if (SelectBoxes.Count < 2)
{
    <div>
        <button type="button" class="btn btn-primary" @onclick="AddSelectBox">Add</button>
    </div>
}

@*Render the corresponding number of select boxes*@
@foreach (var box in SelectBoxes)
{
    <div>
        <select class="[email protected](box + 1)">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>

    </div>
}

@code {

    // this is your view model, ie. a collection of "IDs" of the select boxes
    List<int> SelectBoxes = new List<int>();


    // this method will add a new item to the collection of select boxes
    void AddSelectBox()
    {
        SelectBoxes.Add(SelectBoxes.Count);
    }
}


Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.