Description
The sample demonstrates the creation of a simple ListBox
based on
a collection. “Add” button is available only when some text is entered in the textbox
— such behavior is provided by the Enable
data binding
The sample demonstrates the creation of a simple ListBox
based on
a collection. “Add” button is available only when some text is entered in the textbox
— such behavior is provided by the Enable
data binding
public class SimpleListModel { public string ItemToAdd { get; set; } public List<string> Items { get; set; } public void AddItem() { Items.Add(ItemToAdd); ItemToAdd = ""; } }
@using PerpetuumSoft.Knockout @model KnockoutMvcDemo.Models.SimpleListModel @{ var ko = Html.CreateKnockoutContext(); } @using (ko.Html.Form("AddItem", "SimpleList", null, new { id = "myform" })) { <span>New item:</span> @ko.Html.TextBox(m => m.ItemToAdd).ValueUpdate(KnockoutValueUpdateKind.AfterKeyDown) <button type="submit" @ko.Bind.Enable(m => m.ItemToAdd.Length > 0)>Add</button> <p>Your items:</p> @ko.Html.ListBox(m => m.Items, new { width = 50, size = 7 }) } <script type="text/javascript"> $('#myform').ajaxForm(); </script> @ko.Apply(Model)
public class SimpleListController : BaseController { public ActionResult Index() { InitializeViewBag("Simple list"); var model = new SimpleListModel { Items = new List<string> { "Alpha", "Beta", "Gamma" } }; return View(model); } public ActionResult AddItem(SimpleListModel model) { model.AddItem(); return Json(model); } }
<form data-bind="submit : function() {executeOnServer(viewModel, '/SimpleList/AddItem');}" id="myform"> <span>New item:</span> <input data-bind="value : ItemToAdd,valueUpdate : 'afterkeydown'" name="ItemToAdd" type="text" /> <button type="submit" data-bind="enable : (ItemToAdd().length > 0)">Add</button> <p>Your items:</p> <select data-bind="options : Items" multiple="multiple" size="7" width="50"></select></form> <script type="text/javascript"> $('#myform').ajaxForm(); </script> <script type="text/javascript"> var viewModelJs = {"ItemToAdd":"","Items":["Alpha","Beta","Gamma"]}; var viewModel = ko.mapping.fromJS(viewModelJs); ko.applyBindings(viewModel); </script>