Simple list

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 original example: http://knockoutjs.com/examples/simpleList.html

Live example

New item:

Your items:

Model

public class SimpleListModel
{
    public string ItemToAdd { get; set; }
    public List<string> Items { get; set; }

    public void AddItem()
    {
        Items.Add(ItemToAdd);
        ItemToAdd = "";
    }
}

Razor

@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)

Controller

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);
    }
}

Html (autogenerated)

<form data-bind="submit : function() {executeOnServer(viewModel, &#39;/SimpleList/AddItem&#39;);}" id="myform">
  <span>New item:</span>
<input data-bind="value : ItemToAdd,valueUpdate : &#39;afterkeydown&#39;" 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>