How to bind asp-items to the model in a select element appended by js dynamically?

Alick Wang 246 Reputation points
2023-06-04T01:20:40.3366667+00:00
$("#List").append("<tr>"              
                + "<td> <select name='dm' asp-items='"+Model.dmdata+"'>"              
                + "</select></td>"
 ......



It doesn't work.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,077 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 53,426 Reputation points
    2023-06-04T17:54:57.11+00:00

    you would render the select list to a javascript object.

    var dmdata = @Html.Raw(JsonSerializer.Serialize(Model.dmdata.Select(o => new {value=o.Value, text=o.text}).ToList()));
    
    dmdata
      .reduce((s,c) => {
          $("<option>")
            .prop("text",c.text)
            .prop("value",c.value)
            .appendTo(s)
          return s;
      },$("<select>"))
      .wrap("tr")
      .appendTo("#list");
    
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Ola Alsafady 0 Reputation points
    2023-06-06T13:21:41.0966667+00:00
    Header 1 Header 2
    Cell 1 Cell 2
    Cell 3 Cell 4
    0 comments No comments