Blazor: Reusable OnSelect Change Event

355 Views Asked by At

Is there a more reusable version of this:

 void OnSelectFoundWithCus(ChangeEventArgs e)
 {
     selectedString = e.Value.ToString();
     DisplayToggle("FoundWithCus");
 }
 async Task DisplayToggle(string DivToToggle)
 {
    if(selectedString == "Yes")
    //if (!isChecked)
    {
        await JSRuntime.InvokeAsync<object>("showElement", new { id = DivToToggle });
        isChecked = !isChecked;
    }
    else
    {
        await JSRuntime.InvokeAsync<object>("hideElement", new { id = DivToToggle });
        isChecked = !isChecked;
    }
 }

I'd like to have one reusable method that I can pass through a string for what Div to hide/show, but it doesn't seem to be an option with a ChangeEventArgs method. There's several controls that the users want toggled between hidden and visible based off option selections (all yes/no). Ideally, I'd rather just have one method that I could use like this:

 void OnSelect(ChangeEventArgs e, string DivToToggle)
 {
     selectedString = e.Value.ToString();
     DisplayToggle(DivToToggle);
 }

Trying to use the method of changing the classes like this:

<div class="@className"></div>

Then

void OnSelect(ChangeEventArgs e)
{
    selectedString = e.Value.ToString();
    if (selectedString == "No")
    {
        className = "form-group row";
    }
    else
    {
        className = "Invisible";
    }        
}

Results in every control using class="@className" being displayed/hidden when any of the controls referencing it select an option.

1

There are 1 best solutions below

0
jnelson On

It looks like I may have asked the wrong question. Basically, I needed to pass additional parameters to a function with a ChangeEventArgs parameter. So far, the first functional version of this I found is this setup (until I can get a non-JavaScript version working):

For the select control:

 <select @onchange='(e  => DisplayToggle(e, "DMGReported"))' class="form-control">
     <option value=" "> </option>
     <option value="Yes">Yes</option>
     <option value="No">No</option>
 </select>

For the C#:

async Task DisplayToggle(ChangeEventArgs e, string DivToToggle)
{
    selectedString = e.Value.ToString();
    if (selectedString == "Yes")        
    {
        await JSRuntime.InvokeAsync<object>("showElement", new { id = DivToToggle });
        selectedString = "";
    }
    else
    {
        await JSRuntime.InvokeAsync<object>("hideElement", new { id = DivToToggle });
        selectedString = "";
    }
}

And for the IJSRuntime:

function hideElement(styleOp) {
    document.getElementById(styleOp.id).style.display = "none";
}
function showElement(styleOp) {
    document.getElementById(styleOp.id).style = null;
    document.getElementById(styleOp.id).style.visibility = "visible";    
}