我从控制器那里得到了回应
[HttpGet]
public JsonResult GetItems(string date)
{
IList<dough> modelList = new List<dough>();
modelList.Add(new dough { Type = "framed" });
modelList.Add(new dough { Type = "unframed" });
modelList.Add(new dough { Type = "soft" });
return Json(modelList, JsonRequestBehavior.AllowGet);
}
以这种方式显示
<table>
<thead>
<tr><th>Waste</th></tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><select data-bind="options: $root.availableWastes, value: Waste, optionsText: 'Type'"></select></td>
</tr>
</tbody>
</table>
结果
主要问题是如何显示从控制器获取的默认值的项目?需要解决什么?
控制器:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetItems(string date)
{
IList<dough> modelList = new List<dough>();
modelList.Add(new dough { Type = "framed" });
modelList.Add(new dough { Type = "unframed" });
modelList.Add(new dough { Type = "soft" });
return Json(modelList, JsonRequestBehavior.AllowGet);
}
}
class dough
{
public string Type { get; set; }
}
Index.cshtml
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-2.2.0.js"></script>
<button data-bind="click: loadItems">Load</button>
<table>
<thead>
<tr><th>Waste</th></tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><select data-bind="options: $root.availableWastes, value: Waste, optionsText: 'Type'"></select></td>
</tr>
</tbody>
</table>
<script>
function MyViewModel() {
var self = this;
self.availableWastes = [{ Type: "framed", score: 0 },
{ Type: "soft", score: 1 },
{ Type: "unframed", score: 2 }];
self.items = ko.observableArray();
var date = new Date();
self.loadItems = function () {
var date = new Date();
debugger;
$.ajax({
cache: false,
type: "GET",
url: "Home/GetItems",
data: { "date": date },
success: function (data) {
var result = "";
self.items.removeAll();
$.each(data, function (id, item) {
self.items.push({ Waste: item.Type });
});
},
error: function (response) {
alert('eror');
}
});
}
}
ko.applyBindings(new MyViewModel());
</script>