简体   繁体   中英

How to have a ViewBag List Dynamic view with is created from JavaScript

I have HTML view which has ViewBag list as you can see in the code below.

                      ``` 
<select asp-for="categoryName" id="CatId" name="purchase[0].categoryName" class="form-control" style="border-radius: 12px; " asp-items="@ViewBag.Pitems">
                                    <option>Select Category</option>
                            </select>         
                             
                           <select asp-for="type" id="typeId" name="purchase[0].type" class="form-control" style="border-radius: 12px; " asp-items="@(new SelectList(string.Empty, "type", "type"))">
                                    <option>Select Type</option>
                             </select>

Now for other page want to use same thing but it is in javascript, When I write this code in Javascript ViewBag is not working

   var counter - 1;          '
<select  class="form-control"  asp-for="categoryName" name="purchase[' + counter + '].categoryName" style="border-radius: 12px; " id="cat1" onchange="change1(' + counter + ', this) asp-items="@ViewBag.Pitems";>' 

This code is showing no value in dropdown, how to code javascript dropdown list which access ViewBag>

You need to serilize the ViewBag data in js function:

var obj = @Html.Raw(Json.Serialize(ViewBag.model));

Take a look at this thread:

https://stackoverflow.com/a/61886045/11965297

Example:

Controller:

public IActionResult Index()
{
    List<ItemsType> type = new List<ItemsType>
    {
        new ItemsType{ TypeId = 1, Type = "A"},
        new ItemsType{ TypeId = 2, Type = "B"},
        new ItemsType{ TypeId = 3, Type = "C"},
    };
    ViewBag.type = type;
    return View();
}

View:

<div id="container">

</div>

Scripts:

<script>
    var types = @Html.Raw(Json.Serialize(ViewBag.type));
    var select = document.createElement("select");
    $(select).attr("name", "purchase[0].type");
    $(select).attr("id", "typeId");
    $(select).addClass("form-control");
    $(select).css("border-radius","12px");
    $.each(types, function (index, type) {
        var option = document.createElement("option");
        option.value = type.typeId;
        option.text = type.type;
        select.append(option);
    })
    $("#container").append(select);
</script>

Result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM