Viewbag in Javascript shows error Uncaught SyntaxError: Unexpected token '<'

Viewbag in Javascript shows error Uncaught SyntaxError: Unexpected token '<'

我正在使用 API 获取数据并将其分配给 VIEW BAG,但在 运行 时显示错误。

List<DevInfo> DevList = await RestApi.Instance.GetAllDevAsync();
var nameT = DevList.Select(a=>a.Name).ToList();
ViewBag.datasourceDevList = nameT;

并在脚本中。

var nameList = <%= new JavaScriptSerializer().Serialize("@ViewBag.datasourceDevList") %>;

我想生成下拉列表。

if (nameList != '') {
                var tableHtml;
                $.each(JSON.parse(nameList), function (index, value) {
                    //tableHtml += "<option value=" + value.Name + ">" + value.Name + "</option>";
                    console.log(value);
                });
                /*$("#selectTrainer").html(tableHtml);*/
                $("#selectTrainer").append(tableHtml);
}

不要在javascript中调用JavaScriptSerializer(),这会使代码看起来很复杂,您可以通过以下方式生成选项:

解决方案 1:使用剃须刀语法

view

<select id="selectTrainer">
    @if (ViewBag.datasourceDevList != null)
    {
        foreach(var option in ViewBag.datasourceDevList)
        {
            <option value="@option.Name">@option.Name</option>
        }
    }
</select>

Sample Solution 1


解决方案 2:将 IEnumerable<SelectListItem> 传递给 @Html.DropDownListFor

使用 IEnumerable<SelectListItem> 元素设置 ViewBag@Html.DropDownListFor 将根据列表项生成选项。

controller

using System.Linq;

ViewBag.datasourceDevList = DevList
    .Select(x => new SelectListItem { Text = x.Name, Value = x.Name } )
    .ToList();

view

@Html.DropDownListFor(m => m.DevID, 
    (IEnumerable<SelectListItem>)ViewBag.datasourceDevList,
    htmlAttributes: new
    {
        @id = "selectTrainer"
    })

Sample Solution 2


参考资料

DropDownList(HtmlHelper, String, IEnumerable)