Introduction
In my previous articles I told you about:
- How to Bind TextBox in various Ways Through Knockout in MVC
- How to Bind Password and Multi Line TextBox Through Knockout in MVC
- How to Bind Checkbox and Dropdown Menu Using Knockout in MVC.
In this article I will tell you how to bind a Multi-Select Drop Down and Radio Buttons Using Knockout in MVC.
Step 1
We are working on the previous application so you don't need to make changes in the previous settings of the application.
First of all we will work on the Model Class of our application. So, add this code in the Model Class:
public List<string> SelectMultipleOptions { get; set; }
public string RadioButtons { get; set; }
Here I created a list of strings named "SelectMultipleOptions".
After that I created another variable named "RadioButtons".
Since we had added this code in the previous application your final code should be like this:
using PerpetuumSoft.Knockout;
using PerpetuumSoft;
using DelegateDecompiler;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MvcApplication20.Models
{
public class Class1
{
public string StringValue { get; set; }
public string PasswordValue { get; set; }
public bool Bool { get; set; }
public List<string> Options { get; set; }
public string DefaultSelected { get; set; }
public List<string> SelectMultipleOptions { get; set; }
public string RadioButtons { get; set; }
}
}
Step 2
Now we will move toward the Controller class of our application and will add some code in this class also. Write this code in the Controller Class:
SelectMultipleOptions = new List<string> { "Bike" },
RadioButtons = "Car"
Here I declared the default value for both SelectMultipleOptions as well as for RadioButtons.
Now your complete code will be like this:
using PerpetuumSoft.Knockout;
namespace MvcApplication20.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new Class1
{
StringValue = "Hello",
PasswordValue = "mypass",
Bool = true,
Options = new List<string> { "Car", "Bike", "Cycle" },
DefaultSelected = "Bike",
SelectMultipleOptions = new List<string> { "Bike" },
RadioButtons = "Car"
};
return View(model);
}
}
}
Step 3
Now we will proceed towards the View Class of our application. Here in this class the controls and their Bindind will be created.
You can update your previous code with this code:
<script src="~/Scripts/knockout-2.3.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/Scripts/perpetuum.knockout.js"></script>
@using PerpetuumSoft.Knockout
@model MvcApplication20.Models.Class1
@{
var ko = Html.CreateKnockoutContext();
}
<table id="maintable">
<tr>
<td>
<h3>HTML controls</h3>
<table>
<tr>
<td>Text value (updates on change):</td>
<td>@ko.Html.TextBox(m => m.StringValue)</td>
</tr>
<tr>
<td>Text value (updates on keystroke):</td>




Upendra Pratap ShahiPosted Mar 25, 2016, 5:37 AM
nice share..