ASP.NET Core / jQuery-尝试显示JSON时出现Uncaught TypeError

时间:2018-11-07 11:32:08

标签: javascript c# jquery asp.net-core

我有一个TCP侦听器,该侦听器正在侦听包含酒店ID和名称的传入JSON字符串,一旦接收到JSON,我想显示酒店列表及其名称作为列表。但是,在chrome控制台中,出现以下错误:

jquery.js:489 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in "[{\"Id\":1,\"Name\":\"Hotel Ritz\"},{\"Id\":2,\"Name\":\"Scandic\"},{\"Id\":3,\"Name\":\"Hotel Villa Provence\"},{\"Id\":4,\"Name\":\"First Hotel Atlantic\"}]"
at isArrayLike (jquery.js:489)
at Function.each (jquery.js:351)
at Object.success (site.js?v=5BUCGd0L7FqRV9EDqjbCXfE3SLPjEtoSfd2jy5c48yU:26)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)

site.js:

const uri = "/api/hotel";

let hotels = null;

$(document).ready(function () {

getData();

});

function getData() {
$.ajax({
    type: "GET",
    url: uri,
    cache: false,
    success: function (data) {
        const tBody = $('#hotels');

        $(tBody).empty();

        $.each(data, function (key, item) {
            const tr = $("<ul></ul>")
                .append($("<li></li>").text(item.name));

            tr.appendTo(tBody);
        });

        hotels = data;
    }
});
}

HotelController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VIABooking.Models;

namespace VIABooking.Controllers
{
[Route("/api/hotel")]
[ApiController]
public class HotelController : ControllerBase
{
    //private readonly DatabaseContext _context;
    private readonly ModelManager modelManager = new ModelManager();

    /*[HttpGet]
    public ActionResult<List<Hotel>> GetAll()
    {      
        return _context.HotelItems.ToList();
    }*/

    [HttpGet]
    public ActionResult<string> GetAll()
    {
        return modelManager.GetHotelList(); 
    }

}
}

HomeController:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using VIABooking.Models;

namespace VIABooking.Controllers
{
public class HomeController : Controller
{

    private readonly ModelManager modelManager = new ModelManager();

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Hotel()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
}

ModelManager.cs:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;sing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace VIABooking.Models
{
public class ModelManager : IModelManager
{
    private readonly TcpConnectionManager tcpManager = new TcpConnectionManager();

    public ModelManager() {}

    public string GetHotelList ()
    {
        return tcpManager.GetHotelList();
    }
}
}

TCPListener.cs:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters.Json;

namespace VIABooking.Models
{
public class TcpConnectionManager
{        
    public string GetHotelList()
    {
        //Sending json to other server

        const int PORT_NO = 5005;
        const string SERVER_IP = "127.0.0.1";

        TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
        NetworkStream ns = client.GetStream();

        string s = "Please send me a list of all hotels!";

        string json = JsonConvert.SerializeObject(s);

        byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(json);

        ns.Write(bytesToSend, 0, bytesToSend.Length);


        //Receiving json from other server

        byte[] buffer = new byte[client.ReceiveBufferSize];

        int bytesRead = ns.Read(buffer, 0, client.ReceiveBufferSize);

        string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead);

        string json2 = JsonConvert.SerializeObject(dataReceived);

        client.Close();
        ns.Close();

        return json2;
    }
}
}

1 个答案:

答案 0 :(得分:1)

您可以使用以下一个选项来解决您的问题:

    客户端上的
  • const hotels = JSON.parse(data)获取js对象 代替字符串
  • dataType: json添加到$.ajax的设置参数中
  • 返回List<Hotel>JsonResult而不是服务器端api/hotels中的字符串。它将响应的 Content-type 更改为 application / json ,因此jquery将自动解析json