【发布时间】:2014-07-11 15:33:43
【问题描述】:
目前我有一个网页,用户可以为它命名并创建新的“游戏”。应该发生的是用户在文本框中输入名称,点击“创建”然后创建游戏。目前,当用户点击 create 时,会生成 GUID 并创建游戏。如果用户将游戏命名为 Test,它应该显示,Game: Test Remove(点击移除移除游戏。)但是游戏被列为,Game: undefined Remove。我怎样才能让它显示用户给游戏的名字? 谢谢你的帮助
这是我的代码
控制器
using PlanningPoker.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace PlanningPoker.Controllers {
public class GMController : ApiController {
private static List<Game> games = new List<Game>() {
new Game() {
ID = Guid.NewGuid(),
Title = "D&D"
}
};
[Route("data/games")]
public IEnumerable<Game> GetAllGames() {
return games;
}
[Route("data/games/create"), HttpPost]
public Guid CreateGame(string title) {
Game g = new Game() {
ID = Guid.NewGuid(),
Title = title
};
games.Add(g);
return g.ID;
}
[Route("data/games/remove"), HttpPost]
public void RemoveGame(Guid id) {
games.RemoveAll(g => g.ID == id);
}
}
}
索引(hmtl)(用户可以在这里创建游戏,创建的游戏在这里显示)
<head>
<title>Planning Poker</title>
<style>
.inlinetext {
display: inline;
}
</style>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Scripts/GameSVC.js"></script>
<script src="Gamelist.js"></script>
<script type="text/javascript">
$(function () {
$('#button').on('click', function (data) {
svc.Game.Add($('#testtxt').val(), function (d) { console.log(d), window.location.reload(); });
});
});
</script>
</head>
<body>
<h3 class='inlinetext'> Create Game: </h3>
<input type="text" id="testtext" name="ime">
<button id="button" >Create</button>
<h4>Games</h4>
<ul data-bind="foreach: { data:$data.games, as:'$game' }">
<li>
Game :
<span data-bind="text: $game.Title"> </span>
<a data-bind="click: function(d,e) { $parent.removeGame(d); }">Remove</a>
</li>
</ul>
</body>
</html>
游戏列表 (js)
function AppViewModel() {
var self = this;
self.games = ko.observableArray([]);
$.getJSON("/data/games", function (d) {
self.games(d);
});
self.removeGame = function (game) {
svc.Game.Remove(game.ID, function () {
$.getJSON("/data/games", function (d) {
self.games(d);
});
});
}
}
$(function () {
ko.applyBindings(new AppViewModel());
});
游戏 SVC
var svc = svc || {
Game: {
Add: function (title, cb) {
$.post('data/games/create/?title='+title, cb);
},
Remove: function (id, cb) {
$.post("data/games/remove/?id=" + encodeURIComponent(id), cb);
}
}
};
【问题讨论】:
标签: javascript knockout.js http-post