How to create a dynamic dropdown in mvc

955 Views Asked by At

How to create a dropdown whose option values are coming from controller. controller will be getting it from database table's any column value.

for example if that dropdown is for selecting country, and i have 3 country in my database table's country column, in dropdown it should show the 3 country. And if I add one more value in country table, that also should come in dropdown.

I am new to MVC an this is found bit difficult. I am using mvc5.

NB: since I already one model is refered inside the view, I cant add the model for this dropdown

1

There are 1 best solutions below

0
On

I have done the same in my own website. This is how I do it:

Firstly, create a action for controller which returns JSON value:

public ActionResult GetCountryNames()
    {
        List<string> CountryNames = new List<string>();
        CountryNames = context.GetCountries(); // your EF context to get countrynames from database
        return Json(CountryNames.ToArray());
    }

Then in your view add this html mark up:

<select id="countrylist" onchange="DoSomething();"></select>

This is your dropdownlist. It has javascript function declared in "onchange" event, if you want to do something when value changes.

Lastly, you need to add your javascript function, which does ajax call to your controller action, gets values and set it to your dropdownlist:

function GetCountryList() {
var serviceURL = '/Home/GetCountryNames';

$.ajax({
    type: "post",
    dataType: "json",
    url: serviceURL,
    success: successFunc,
    async: false,
    error: errorFunc
});

function successFunc(data, status) {
    var countrylist = $('#countrylist');
    countrylist.empty();
    for (var i = 0; i < data.length; i++) {
    var $option = $("<option>", { id: "option" + i });
    $option.append(data[i]);
    countrylist.append($option);
    }
}

function errorFunc(data, status) {
    alert('error');
    }
}

And when your document is ready, run function GetCountryList(). Probably easiest is to do it with jQuery. Like this:

   <script type="text/javascript">
       $(document).ready(function () {
       GetCountryList();
       });
   </script>