0

Good day,

I am populating a dropdown using ajax. The data is coming from my mvc controller

   [HttpGet]
    public ActionResult GetResult()
    {
        var result = _IInterface.GetList();
        //result is a list that have name, lastname and Id
        if (result == null) return null;
        var jsons= Json(result, JsonRequestBehavior.AllowGet);
        return jsons;
    }

In my front end my ajax call is getting the data from my action result without any problem. This is my part of my view

@using (Ajax.BeginForm("CreatePaper", new AjaxOptions()
{
OnSuccess= "ajaxSuccess"
}))
{
 <select id=" countryDropDownList">
        <option value="Select">Select</option>
    </select> 

The ajax call

    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "/Author/GetAuthors",

            success: function (data) {

                var options = '';
                var mySelect = $('#countryDropDownList');
                for (var i = 0; i < data.length; i++) {
                    options += '<option value="' + data[i].Name + " " + data[i].LastName + '">' + "test" + '</option>'; 

                }
                console.log(options);   
                $("#countryDropDownList").appendTo(options);
            },
            failure: function () {
                alert("sdfgsdgsdfd");                  
            }
        });          
});

When I inspect the console.log(options) I get this:

<option value="asdfasd sagasdg">test</option><option value="Select">Select</option>

my problem is that my code is not appending the options. What is wrong?thanks

I already looked for in different places:
AJAX Call For Dropdown Lists In MVC

Append items to dropdown jQuery / Ajax

How do I add options to a DropDownList using jQuery?

1 Answers1

0

First off, you have a leading space in your id attribute of your <select> list. This may have been a typo when you copied your code over, but if it is that way in your code - that will be problematic, as $("#myId") will not pick up <elem id=" myId"></elem>

Secondly, you should be using .append() not .appendTo() - there is a great explanation of the difference between the two in this article

You should also return [] rather than null from your MVC controller if there are none found. Otherwise, you will say var i = 0; i < data.length;... which will evaluate to null.length which will throw a type error

mhodges
  • 10,938
  • 2
  • 28
  • 46