Value and ID in the DropDown Cascade

1

Reference that can help you understand the code.

DropDown Waterfall

This part here I pass the values that will be added in the second DropDown

var classesList = this.GetClasses(Convert.ToInt32(CanalMassivo));
    var classesData = classesList.Select(m => new SelectListItem()
    {
        Value = m.idSegmento.ToString(),
    });

    var states = classesData.Select(m => m.Value).ToList();
    return Json(states, JsonRequestBehavior.AllowGet);

In the Value = m.idSegmento.ToString() part and the value that appears in the DropDown as the value that the controller receives.

How could I do to pass the description in DropDown and the controller receive the id value?

I tried this way

        Text = m.descricao.ToString(),
        Value = m.idSegmento.ToString(),
    });

    var states = classesData.Select(m => m.Text).ToList();

But it generates this error

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'idCanalIndicadoresMassivo'.
    
asked by anonymous 30.11.2015 / 12:24

1 answer

2

If you want to use SelectListItem() change your action to this:

var classesList = this.GetClasses(Convert.ToInt32(CanalMassivo));
    var classesData = classesList.Select(m => new SelectListItem()
    {
        Value = m.idSegmento.ToString(),
        Text = m.descricao
    });
    //Não selecione somente o texto, você precisará dos dois.
    return Json(states, JsonRequestBehavior.AllowGet);

And in your call ajax , where you populate DropDown , you change to pass idSegmento on value and descricao on option , like this:

   $.each(data, function (i, state) {
         //Create new option
         var option = $('<option value="'+state.Value+'">' +state.Text+ '</option>');
         //append state states drop down
         stateDropdown.append(option);
   });

In this way you will see the description, and DropDown will have the value of idSegmento .

    
01.12.2015 / 13:13