【问题标题】:ASP.NET MVC - Using JavaScriptStringEncode() with anonymous Type and JqueryASP.NET MVC - 使用带有匿名类型和 Jquery 的 JavaScriptStringEncode()
【发布时间】:2021-02-27 21:44:36
【问题描述】:

我尝试使用 JavaScriptStringEncode 库保护字符串,但它显示以下错误:

无法从“System.Collections.Generic.IEnumerable>”转换为“字符串”

控制器:

    public JsonResult GetBarcosNaoVinculados(string usuarioId)
    {         
        var linkedboatds= this._boatsAppService.GetUnboundBoats(usuarioId)
                            .Select(boats=> new { boats.Name, boats.Id });

        return Json(HttpUtility.JavaScriptStringEncode(linkedboatds), 
        JsonRequestBehavior.AllowGet);
    }

为了解决这个问题,我将它转换为字符串,使用toString(),但是当我进入jQuery函数时,我得到了以下错误:

未捕获的 TypeError: 无法使用 'in' 运算符在 in 中搜索 'length' System.Linq.Enumerable+WhereSelectListIterator2[BR.Rve.Application.ViewModels.Embarcacao.BarcoViewModel,\u003c\u003ef__AnonymousType112[System.String,System.Guid]]

jQuery 脚本:

function searchForAvailableBoats {
        $ddlBarcosDisponiveis.find("option").remove();
        function callBack(data, status) {
            if (data && data.length) {
                //Add data to dropdown 
                var options = ""
                $.each(data, function (index, item) {
                    options += '<option value="' + item.Id + '">' + item.Nome + '</option>';
                });

                $ddlBarcosDisponiveis.append(options);
            }
        }
        sistema.ajax.get('AdminUser/GetBarcosNaoVinculados?usuarioId=' + getUserId(), callBack);
    }

如何在控制器或 jQuery 中解决这个问题?

【问题讨论】:

    标签: c# jquery json asp.net-mvc


    【解决方案1】:

    您似乎在字符串上使用$.each。你原来的错误:

    无法从“System.Collections.Generic.IEnumerable>”转换为“字符串”

    您可以通过.ToString() 将其转换为字符串来解决此问题。然后您在该数据上运行$.each,这不起作用,因为$.each 只能用于对象。如果您在运行 $.each 之前对数据进行 json 解析,它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多