Search code examples
asp.net-mvcdropdownbox

Can't display data in a dropdown with MVC


I have a dropdown on my page that displays data hardcoded in the class.

I have the following class called state:

public class State
{
    public string StateCode {get; set;}
    public string StateName { get; set; }

    public static IQueryable<State> GetStates()
    {
        return new List<State>
        {
            new State{
                StateCode="DE",
                StateName="Delaware"
            },
            new State{
                StateCode="NJ",
                StateName="New Jersey"
            },
            new State{
                StateCode="PA",
                StateName="Pennsylvania"
            }

        }.AsQueryable();
    }
}

My Home controller has the following actions:

public ActionResult Index()
    {
        return View();
    }

    public ActionResult StateList()
    {
        IQueryable states = State.GetStates();
        if (HttpContext.Request.IsAjaxRequest())
        {
            return Json(new SelectList(states,
                "StateCode",
                "StateCode"), JsonRequestBehavior.AllowGet
                );
       }
        return View(states);
    }

and here is what I have in my view:

@section scripts {
<script type="text/javascript">
$(function () {
    $.getJSON("/Home/States/List", function (data) {
        var items = "<option>Please Select</option>"
        $.each(data, function (i, state) {
            items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
        });
        $("States").html(items);
    });


});

</script>
}

@using (Html.BeginForm())
{

<label for="States"></label>
<br />
<select id="States" name="States"></select>

}

I also added this to my routing:

routes.MapRoute(
            "StatesList",
            "Home/States/List",
            new { controller = "Home", action = "StateList" }
        );

I do not get any errors but also no data shows up in my dropdown box. I tried debugging my controller and I can see that the state data gets into the object states inside the action. Can anyone help me diagnose the problem?


Solution

  • $("States").html(items); needs to be $("#States").html(items); (the hash indicates a jQuery ID Selector)

    Side notes:

    1. IQueryable GetStates() should really be IEnumerable GetStates() (refer linked documentation)
    2. There is no need for the extra overhead of creating a SelectList in the StateList() method. It can be simply return Json(states, JsonRequestBehavior.AllowGet); and then in the ajax success function: items += "<option value='" + state.StateCode + "'>" + state.StateName + "</option>";
    3. Currently if the first option ("Please Select") is selected, it will post back the value Please Select which I suspect is not what you want. Intead, give the option a null value (which you can then use in conjunction with a [Required] attribute to force a selection). For example: var items = $('<option>Please Select</option>').val('');