Knockout从控制器中选择值

时间:2016-03-01 17:27:23

标签: asp.net-mvc-4 knockout.js

我从控制器那里得到了回应

    [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>

结果

enter image description here

主要问题是如何显示从控制器获取的默认值的项目?需要解决什么?

enter image description here

控制器:

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>

1 个答案:

答案 0 :(得分:1)

看起来您想要预先选择值。

使用Type name和Waste更新self.items到一个observable:

self.items.push({ Waste: ko.observable(item.Type), Type: item.Type });

然后在optionsValue绑定中使用它:

<select data-bind="options: $root.availableWastes, value: Waste, optionsText: 'Type', optionsValue: 'Type'">

截图:

enter image description here

相关问题