如何使用 JavaScript 创建 ViewBag 列表动态视图

问题描述

我有 HTML 视图,其中包含 ViewBag 列表,如下面的代码所示。

                      ``` 
<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>

现在对于其他页面想要使用相同的东西,但它是在 javascript 中,当我在 Javascript 中编写此代码时,ViewBag 不起作用

   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";>' 

这段代码在下拉列表中没有显示任何值,如何编写访问ViewBag的javascript下拉列表>

解决方法

需要在js函数中对ViewBag数据进行序列化:

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

看看这个线程:

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

示例:

控制器:

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();
}

查看:

<div id="container">

</div>

脚本:

<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>

结果:

enter image description here