无序列表在HTML中被视为未定义

时间:2015-10-08 05:00:32

标签: c# html ajax api rest

我正在尝试使用AJAX构建REST API。 我的C#代码看起来像这样。

using System;
using System.Collections.Generic;
using System.Linq; 
using System.Net;
using System.Net.Http;
using System.Web.Http; 
using WebApplication2.Models;
using System.IO;
using System.Globalization;

namespace WebApplication2.Controllers
{
public class DefaultController : ApiController
{
    List<Default>players = new List<Default>();
    string path = Path.Combine(Directory.GetCurrentDirectory(), "\\players.txt");

    public IHttpActionResult GetAllPlayers()
    {
        String line;
        StreamReader file = new StreamReader(path);
        string[] data;
        while ((line = file.ReadLine()) != null)
        {
            data = line.Split(',');
            Default player = new Default(data[0],data[1],data[2],data[3],DateTime.ParseExact(data[4],
                "yyyy-mm-dd", CultureInfo.InvariantCulture));
            players.Add(player);
        }
        file.Close();
        return Ok (players); 
    }

我的HTML网页代码如下所示

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  <div>
     <h2> All Players</h2>
       <ul id="players"/>

  </div>

  <div>
    <br />
    <h2> Search or Delete </h2>
    <select name="options_for_search_delete">
        <option value="id">ID</option>
        <option value="name">Name</option>
    </select>
    <input type = "text" id="data" size="5"/>
    <input type = "button" value="Search" onclick = "search()" />
    <input type = "button" value="Delete" onclick = "find()" />
    <br />
    <p id="players"/>

  </div>

  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
  <script>

    var uri = 'api/default';
    $(document).ready(function () {
        $.getJSON(uri).done(function(data){
              //success:function(data){
                $.each(data,function(key,item){
                    $('<li>',{text:format(item)}).appendTo($('#players'));

                });
            });
    });

    function format(item){
        return item.reg + "," + item.first + " " + item.last + "," + item.team;
    }

   </script>
 </body>
</html>

当我访问api / default页面时,输出符合预期。但是,当我访问players.html时,无序列表显示为未定义。我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

尝试

<ul id="players"></ul> 

因为它是一个块元素,id对于元素应该是唯一的。