【问题标题】:Viewbag in Javascript shows error Uncaught SyntaxError: Unexpected token '<'Javascript 中的 Viewbag 显示错误 Uncaught SyntaxError: Unexpected token '<'
【发布时间】:2021-10-27 02:13:34
【问题描述】:

我正在使用 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 jquery .net-core model-view-controller


    【解决方案1】:

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

    解决方案 1:使用 razor 语法

    查看

    <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&lt;SelectListItem&gt; 传递给 @Html.DropDownListFor

    ViewBag 设置为IEnumerable&lt;SelectListItem&gt; 元素。 @Html.DropDownListFor 将根据列表项生成选项。

    控制器

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

    查看

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

    Sample Solution 2


    参考文献

    DropDownList(HtmlHelper, String, IEnumerable)

    【讨论】:

      猜你喜欢
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多