The model has a field - an array of ingredients, the ingredient has 3 properties: IngredientId, IngredientName, Weight. To enter Weight, a text field is used, for IngredientId, a DropDownList is used, the value of which SelectList is obtained via the ViewBag via the controller (just a list of all the ingredients in the database). Clicking on addlink should add a block for a new ingredient. And if there is no problem with adding a text field for Weight, then there is a problem with the drop-down list. I do not know how to transfer the array ViewBag.ingredients to the script, and how to fill them in the drop-down list in the script.

Can someone tell me how to do this better?

Below is the code from the view and the script.

View code

<div id="ingredientBlock" class="form-group"> @Html.Label("Ingredients", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="ingredientItem col-md-10"> @Html.DropDownListFor(model => model.Ingredients[0].IngredientId, new SelectList(ViewBag.ingredients, "IngredientId", "IngredientName"), new { @class = "form-control" }) <input type="text" name="Ingredients[0].Weight" class="form-control" /> </div> </div> <p><a class="" id="addLink">Add new ingredient</a></p> 

Javascript code

 @section Scripts { <script type="text/javascript"> $(function () { var i = 0; $('#addLink').click(function () { i++; var ingredientBlock = "<label class='control-label col-md-2'>Ingredient " + (i + 1) + " </label>" + "<div class='ingredientItem col-md-10'>" + "<select class='form-control' data-val='true' id='Ingredients_" + i + "__IngredientId' name='Ingredients[" + i + "].IngredientId'>" + "</select>" + "<input class='form-control' type='text' name='Ingredients[" + i + "].Weight'/>" + "</div>"; $('#ingredientBlock').append(ingredientBlock); }) }) </script> } 

    1 answer 1

     $(function () { var i = 0; $('#addLink').click(function () { i++; var ingredientBlockHTML = "<label class='control-label col-md-2'>Ingredient " + (i + 1) + " </label>" + "<div class='ingredientItem col-md-10'>" + "<select class='form-control' data-val='true' id='Ingredients_" + i + "__IngredientId' name='Ingredients[" + i + "].IngredientId'>" + "</select>" + "<input class='form-control' type='text' name='Ingredients[" + i + "].Weight'/>" + "</div>"; var ingredientBlock = $(ingredientBlockHTML); // возьмСм содСрТимоС сСлСкта ΠΈΠ· ΠΏΠ΅Ρ€Π²ΠΎΠ³ΠΎ Π±Π»ΠΎΠΊΠ° ingredientBlock.find("select").html($(".ingredientItem select").eq(0).html()); $('#ingredientBlock').append(ingredientBlock); }); }); 
    • Thank you very much - Tiemich