Passing values to html dropdown

How can I pass values from my query controller to my html view dropdown list. I just want to use a query to see values from dropdown and from my query I have columns id and names the id will be hidden on dropdown and names are only visible because I have a target that might be needing the unique id for my updating.

Currently here my pseudo code to read my controller:

<html>
    <select id="names" onclick="getNames()" style="width:200px; height:35px; margin-left:700px">
        <option value="" disabled selected>Names</option>
    </select>
</html>

<script>
    function getNames() {
        //alert("here");
        $.ajax({
            url: '/Home/showData',
            type: 'GET',

            dataType: 'json',
            success: function (data) {
                var row = '';
                $.each(data, function (i, item) {
                    row += '<option style="display:none;" value=' + item.id + '> ' + item.id + '</option>';
                        + '<option value=' + item.name + '> ' + item.name + '</option>';

                });
                $('#names').html(row); // override previous results
            },

            error: function (jqXhr, textStatus, errorThrown) {
                console.log(errorThrown.toString());
            }
        });
    }
</script>

I already build my query to my controller that returns json:

public ActionResult showData()
    {
        //Load mgr list table from MySql
        List<Details> listItems = new List<Details>();
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(constr))
        {
            string query = "SELECT id, concat(f_name,', ',l_name) as names FROM tblInfo";
            using (MySqlCommand cmd = new MySqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (MySqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        try
                        {
                            listItems.Add(new empDetails
                            {            
                                id = Convert.ToInt32(sdr["id"]),                        
                                name = sdr["names"].ToString(),                                   
                            });
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("An error occurred: '{0}'", e);
                        }
                    }
                }
                con.Close();
            }
        }
        return Json(listItems, JsonRequestBehavior.AllowGet);
    }

1 answer

  • answered 2018-11-08 07:34 Tetsuya Yamamoto

    You have several issues on the AJAX call:

    1) The <select> selector uses class name instead of element name (at the time of original version). Use $('#names') instead.

    2) You're creating option list for both id and name separately. You can use value attribute set to the id and the text set as name.

    Therefore, the AJAX callback to populate <select> element should be like this:

    $.ajax({
        url: '/Home/showData',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var ddl = $('#names');
            ddl.empty(); // clear existing values
            $.each(data, function (i, item) {
                ddl.append($('<option>', {
                   value: item.id,
                   text: item.name
                }, '</option>'))
            });
        },
        error: function (jqXhr, textStatus, errorThrown) {
            console.log(errorThrown.toString());
        }
    });
    

    However, if the dropdown should be populated from page load (i.e. after calling return View() from controller side), you should use List<SelectListItem> for option lists and DropDownListFor to create <select> element, and pass the option list to either ViewBag or a List<SelectListItem> viewmodel property:

    Controller action

    ViewBag.ListItems = listItems.Select(x => new SelectListItem { Text = x.name, Value = x.id }).ToList();
    

    View

    @Html.DropDownListFor(model => model.names, ViewBag.ListItems as IEnumerable<SelectListItem>, new { style="width:200px; height:35px; margin-left:700px" })