1

I am working in MVC and I have to bind dropdown values to an array in javascript. How do I do that?

dropdown list-

Html.DropDownListFor(m => m.MyActivityRequest.ToMonth, Model.MonthNames, new { @id = "monthToSelect" })

Javascript function:

$(document).ready(function(){ 
        $("#yearToSelect").change(function(){
            var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
            var date = new Date();
            var monthVar = date.getMonth();
            var yearVar = date.getFullYear();
            if ($(this).val() < yearVar ){
                $("#monthToSelect").find('option').remove();
                for( i = 0; i < 12; i++ ){          
                    $("#monthToSelect").append($("<option>",{
                        value: months[i],
                        text: months[i]
                    }));
                };
            }

you can see that the the array- 'months' is hard coded as of now. I want to dynamically bind the dropdown values to this array.

Amadan
  • 191,408
  • 23
  • 240
  • 301
Atharva
  • 53
  • 2
  • 2
  • 5
  • from where you are getting these month values? you can create new array out of it or use the new array as it is. – Bhushan Kawadkar Apr 28 '15 at 04:22
  • You `@Html.DropDownListFor()` suggests you already have the month names (in `Model.MonthNames`). What are you actually trying to do? –  Apr 28 '15 at 04:25
  • Actually Ii was just supposed to iterate through the dropdown list values- it solved my prob: `var months = new Array(); $('#monthSelect option').each(function() { months.push($(this).text()); });` – Atharva Apr 28 '15 at 09:21

2 Answers2

1

Js Fiddle Demo.

Inside your code place the below code appropriately.

Better Approach:

var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var option = '';

for (i=0;i<months.length;i++){
   option += '<option value="'+ months [i] + '">' + months [i] + '</option>';
}

$('#monthToSelect').append(option);

Refered from here.

Community
  • 1
  • 1
RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
0

I think you have to pass the month list from controller. So in javascript you can make an ajax call and return the same list of months. You can use this list instead of array- 'months' in your javascript function.

Spider man
  • 3,224
  • 4
  • 30
  • 42