asp.net mvc - How to create a dynamic dropdown in mvc -
how create dropdown option values coming controller. controller getting database table's column value.
for example if dropdown selecting country, , have 3 country in database table's country column, in dropdown should show 3 country. , if add 1 more value in country table, should come in dropdown.
i new mvc found bit difficult. using mvc5.
nb: since 1 model refered inside view, cant add model dropdown
i have done same in own website. how it:
firstly, create action controller returns json value:
public actionresult getcountrynames() { list<string> countrynames = new list<string>(); countrynames = context.getcountries(); // ef context countrynames database return json(countrynames.toarray()); }
then in view add html mark up:
<select id="countrylist" onchange="dosomething();"></select>
this dropdownlist. has javascript function declared in "onchange" event, if want when value changes.
lastly, need add javascript function, ajax call controller action, gets values , set 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(); (var = 0; < data.length; i++) { var $option = $("<option>", { id: "option" + }); $option.append(data[i]); countrylist.append($option); } } function errorfunc(data, status) { alert('error'); } }
and when document ready, run function getcountrylist(). easiest jquery. this:
<script type="text/javascript"> $(document).ready(function () { getcountrylist(); }); </script>
Comments
Post a Comment