ASP.NET MVC - Using JavaScriptStringEncode() with anonymous Type and Jquery

Viewed 110

I tried to protect a string with the JavaScriptStringEncode library and it is showing the following error:

Cannot convert from 'System.Collections.Generic.IEnumerable<<anonymous type: string Nome, System.Guid Id>>' to 'string'

Controller:

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

To solve this, I converted it to string, using toString (), but when I get to the jQuery function, I get the following error:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in System.Linq.Enumerable+WhereSelectListIterator2[BR.Rve.Application.ViewModels.Embarcacao.BarcoViewModel,\u003c\u003ef__AnonymousType112[System.String,System.Guid]]

enter image description here

jQuery script:

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

How could I solve this problem in the controller or in the jQuery?

1 Answers

It seems like you're using $.each on a string. Your original error:

cannot convert from 'System.Collections.Generic.IEnumerable<<anonymous type: string Nome, System.Guid Id>>' to 'string'

You got around this by converting it to a string via .ToString(). You then ran the $.each on that data, which wouldn't work because $.each can only be used on objects. If you do a json parse of the data before running the $.each it should work.

Related