- Suggestions please for finishing multi select list date in MVC Razor and Knockout
- @{
- var yearOptions = Enumerable.Range(1930, 2010-1930+1);
- var monthOptions = System.Globalization.DateTimeFormatInfo.CurrentInfo
- .MonthNames
- .TakeWhile(x => x != String.Empty)
- .Select((x,i) => new
- {
- Value = i,
- Text = x
- });
- }
- <div id="the_model">
- <form>
- <div class="editor-row">
- <label>Date of Birth</label>
- @Html.HiddenFor(m => m.BirthDate, new { data_bind = "value: birthDate" })
- <select data-bind="options: yearOptions, value: birthDateYear, optionsCaption: 'year'"></select>
- <select data-bind="enable: birthDateYear, options: monthOptions, optionsValue: 'Value', optionsText: 'Text', value: birthDateMonth, optionsCaption: 'month'"></select>
- <select data-bind="enable: birthDateMonth, options: dayOptions, value: birthDateDay, optionsCaption: 'day'"></select>
- </div>
- </form>
- </div>
- <script type="text/javascript">
- function daysInMonth(month, year) {
- return new Date(year, month, 0).getDate();
- }
- var yearOptions = @Html.Raw(Json.Encode(yearOptions));
- var monthOptions = @Html.Raw(Json.Encode(monthOptions));
- var TheModel = function () {
- var self = this;
- this.birthDate = ko.observable('@Model.BirthDate');
- this.birthDateYear = ko.observable();
- this.birthDateMonth = ko.observable();
- this.birthDateDay = ko.observable();
- this.dayOptions = ko.observableArray([]);
- this.submit = function () {
- // validate and post
- };
- this.birthDateYear.subscribe(function (val) {
- console.log('birthDateYear: ' + val);
- if(parseInt(val) > 0) {
- self.fillDayOptions();
- }
- });
- this.birthDateMonth.subscribe(function (val) {
- console.log('birthDateMonth: ' + val);
- if(parseInt(val) > 0) {
- self.fillDayOptions();
- }
- });
- this.birthDateDay.subscribe(function (val) {
- console.log('birthDateDay: ' + val);
- if(parseInt(val) > 0){
- self.birthDate(getBirthDate(self.birthDateYear(), self.birthDateMonth(), val));
- }
- });
- this.fillDayOptions = function() {
- //self.birthDateDay({});
- var month = self.birthDateMonth();
- var year = self.birthDateYear();
- if(month && year) {
- self.dayOptions([]);
- for(var i = 0; i < daysInMonth(month, year); i++) {
- self.dayOptions.push(i + 1);
- }
- }
- //self.birthDateDay(null);
- };
- var viewModel = new TheModel();
- ko.applyBindings(viewModel, document.getElementById("the_model"));
- </script>