unbalanced
unbalanced

Reputation: 1202

Can't Filling DropDownList with Ajax in MVC

Everything seems OK but value shows empty.. I have 2 dropdownlist, when I choose first one, I got the index and used ajax to fill other dropdownlist.. But problem is that I dont have result.. loop that is in ajax, doesnt work.. and I checked web tool of firefox, result seems empty, but in C# code, the list has items..

so here is my ajax

        $.ajax({
            url: "@Url.Action("ElectionList", "Home")",
            type: "GET",
            dataType: "json",
            data: { electionTypeId: selectedId },

        success: function (data) {


            if (data != null) {
   //HERE IS WORKING
                alert("OK");

                electionCombo.html('');
                $.each(data, function (index,item) {
     //here is not working !!! 
                    alert("hobaaa: " + index);  
                    alert("data: " + item.Text);
                    //    alert(option.ID + "  " + option.politicName);
                    //  electionCombo.append($('<option></option>').val(option.Value).html(option.Text));
                });

            }

here is my c# code

  [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult ElectionList(int electionTypeId)
    {


        var service = new EvoteServicesProviderClient();


        try
        {
        var electtionType = service.getAllElectionTypes().FirstOrDefault(e => e.ID == electionTypeId);

           var  res =
                service.searchElectionByType(electtionType.electionTypeName)
                    .ToList()
                    .Where(e => e.startDate >= DateTime.Now)
                    .Select(e => new SelectListItem
                    {
                        Value = e.ID.ToString(),
                        Text = e.politicName
                    });


            var list = new SelectList(res, "Value", "Text");
            return Json(list, JsonRequestBehavior.AllowGet);

         //   return Json(new { success = true, result = list },
           //      JsonRequestBehavior.AllowGet); 

        }
        catch{}

        return Json(new { success = false, message = "An error occured" }, JsonRequestBehavior.AllowGet);


    }

this is the html side

@using (Html.BeginForm("ElectionList", "Home", FormMethod.Post, new {@class = "form-horizontal", id = "electionlistform"}))
{
    @Html.LabelFor(m => m.SelectedElectionId, new {@class = "col-md-2 control-label"})
    @Html.DropDownListFor(m => m.SelectedElectionId, Model.ElectionList, new {@class = "form-control", id = "electionList"})
    @Html.ValidationMessageFor(m => m.SelectedElectionId)
}

As I wrote, the list is not empty (in actionresult ElectionList)

What I am missing?

Upvotes: 0

Views: 608

Answers (2)

Jorge F
Jorge F

Reputation: 693

What I do when I need to fill a dropdown is the same as you, but I'm using a for loop instead of each (maybe it's the same but for me it's working). And by the way, in your ajax code sample you are not closing the ajax function. Hope in your real code it's okay.

   $.ajax({
            url: "@Url.Action("ElectionList", "Home")",
            type: "GET",
            dataType: "json",
            data: { electionTypeId: selectedId },

        success: function (data) {


            if (data != null) {
   //HERE IS WORKING
                alert("OK");

                electionCombo.html('');
                for (i in data) {
                    var result = data[i];
                    //  electionCombo.append($('<option></option>').val(result.Value).html(result.Text));
                }

            }
   });

By the way, if it's still not working , you could try a ViewModel with the options you need

public class ViewModelExample
{
    public Int32 ValueOption { get; set; }
    public String TextOption { get; set; }
}

And use it in your list instead of selectlist. With viewmodels I don't have problems getting the values with json.

Upvotes: 1

Mathieu Labrie Parent
Mathieu Labrie Parent

Reputation: 2606

Try this :

$.each(data, function () {
 //here is not working !!! 
                alert("hobaaa: " + this.Value);  
                alert("data: " + this.Text);
 });

You can access the property directly because it's json.

UPDATE

Just return the list server side :

var  res =
            service.searchElectionByType(electtionType.electionTypeName)
                .ToList()
                .Where(e => e.startDate >= DateTime.Now)
                .Select(e => new SelectListItem
                {
                    Value = e.ID.ToString(),
                    Text = e.politicName
                });


                return Json(res, JsonRequestBehavior.AllowGet);

Upvotes: 2

Related Questions