Home > Software design >  How to dynamically create a C# Select TagHelper with JavaScript
How to dynamically create a C# Select TagHelper with JavaScript

Time:08-08

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 ><input id="setLeadCheckbox" type="checkbox" /></td>
     <td ><i ></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>

CodePudding user response:

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.

CodePudding user response:

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