How to dynamically create a C# Select TagHelper with JavaScript

Viewed 47

I have a button then when clicked creates a table row with a select element inside of it. I want to insert a tag helper dynamically using javascript. Is there a way to insert a TagHelper via javascript or am I just going to have to do it the long way and build out the select?

 function createNewRow() {
     var row = `<tr>
     <td><select></select></td>
     <td class="rowControl"><input id="setLeadCheckbox" type="checkbox" /></td>
     <td class="trash-cell"><i class="fa-regular fa-trash-can fa-2x"></i></td>
     </tr>`;

     $('#staffTable').append(row);
 }

I instead want to use the built in .NET Core Select Tag Helper

<select asp-for="SelectedEmployeeId" asp-items="Model.Employees"></select>
2 Answers

TagHelpers are "executed" server-side and they generate html that is then sent to the browser. Javascript runs on the browser/client-side, so you cannot create a TagHelper or any razor syntax from javascript.

You can't do it that way. TagHelpers are interpreted. In other words, Razor must see them as actual tags in order to replace them. Here, it's just a JS string, and Razor will not mess with that.The tag helper simply doesn't provide output within a <script> tag, <script> leaves the tag helper unchanged.

You can refer to this link to Dynamically create a drop-down list with JavaScript/jQuery.

Related