0

I have a function that insert a tr/td. I need to insert a @Html.DropDownList but this code isn't work. I'm developing a system using C#, bootstrap with Visual Studio.

    function AddItem() {
    var nItem = Number($("#nItem").val()) + 1;
    $("#nItem").val(nItem);
    var div = document.createElement('tr');
    div.innerHTML = '<td><input type="text" class="item-control" id="Item" name="Item" value="' + nItem + '" style="width:32px;background-color: #e9e9e9;text-align: center" readonly /></td>';
    div.innerHTML += '<td colspan="2"><input type="text" class="item-control Qtd" id="Qtd_' + nItem + '" name="Item" value="0" /></td>';
    div.innerHTML += '<td colspan="2">@Html.DropDownList("UnMedId", null, "-", htmlAttributes: new { id = "UnMed_", Name = "Item", @class = "form-control" })</td>';
    document.getElementById("itens").appendChild(div);
}

Thanks!

Tommy
  • 39,592
  • 10
  • 90
  • 121
user3169822
  • 133
  • 1
  • 7
  • 1
    Razor syntax is parsed on the server side while JavaScript is processed on the client side. You should investigate how to return a PartialView from your controller and use jQuery to make an AJAX request to that controller endpoint to update your HTML. Also updated those tags @Taplar :) – Tommy May 27 '20 at 23:21
  • I include the script in .cshtml – user3169822 May 27 '20 at 23:27
  • 1
    https://stackoverflow.com/a/1570138/130387 - here is an example that should help you add razor generated HTML from an AJAX request – Tommy May 28 '20 at 00:21

1 Answers1

0

Thanks for all. I use Json in controller and use a loop to create a select. In controller:

var UnMedId2 = new SelectList(db.UnMeds, "UnMedId", "Simbolo");
ViewBag.UnMedId2 = JsonConvert.SerializeObject(UnMedId2);

In JavaScript:

var sel = '<select name="cars" id="cars">'
    var UnMed = @Html.Raw(ViewData["UnMedId2"]);
    for (var i = 0; i < UnMed.length; i++) {
        sel += '<option value="' + UnMed[i].Value + '">' + UnMed[i].Text + '</option>';
    }
    sel += '</select >'

Thanks

user3169822
  • 133
  • 1
  • 7