Fill Dropdownlistfor dynamically with Jquery?

Asked

Viewed 553 times

3

I’m trying to fill one DropDownListFor dynamically. This DropDownListFor eh to display the cities of the state, for example: The user chooses the state and in this DropDown the cities of that state are displayed. The problem is that in the model the SelectListItem of the cities is empty and when I rescan the page, and so is giving the following Exception:

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'cidadeSelected'.

How to solve this ?

Model

    //estado
    public IEnumerable<SelectListItem> estados { get; set; }    
    public IEnumerable<long> estadoSelected { get; set; }
    //
    //cidade
    public IEnumerable<SelectListItem> cidades             { get; set; }
    [Required(ErrorMessage = "Selecione a cidade")]
    public IEnumerable<long> cidadeSelected                { get; set; }
    //

HTML

<div class="form-group">
                            <div class="col-md-10">
                                <label for="@Html.IdFor(model => model.estadoSelected)" class="cols-sm-2 control-label">Estado </label>
                                @Html.DropDownListFor(model => model.estadoSelected, Model.estados, "-Escolha o estado-", new { Class = "form-control", data_placeholder = "Selecione o estado" })
                                @Html.ValidationMessageFor(model => model.estadoSelected)
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-10">
                                <label for="@Html.IdFor(model => model.cidadeSelected)" class="cols-sm-2 control-label">Condado </label>
                                @Html.DropDownListFor(model => model.cidadeSelected, Model.cidades, new { Class = "form-control", data_placeholder = "Selecione a cidade" })
                                @Html.ValidationMessageFor(model => model.cidadeSelected)
                            </div>
                        </div>

2 answers

2

Model

public class CascadingDropDownSampleModel
    {

        public IDictionary<string, string> Makes { get; set; }
    }

Controller

 public class CascadingDropDownSampleController : Controller
    {
        #region "Public Actions"


        [HttpGet]
        public ActionResult Index()
        {
            IDictionary<string, string> makes = GetSampleMakes();
            CascadingDropDownSampleModel viewModel = new CascadingDropDownSampleModel()
            {
                Makes = makes
            };

            return View(viewModel);
        }

        public ActionResult GetSampleModels(string selectedMake)
        {
            IDictionary<string, string> models = GetSampleModelsFromSelectedMake(selectedMake);
            return Json(models);
        }


        public ActionResult GetSampleColors(string selectedModel)
        {
            IDictionary<string, string> colors = GetSampleColorsFromSelectedModel(selectedModel);
            return Json(colors);
        }

        #endregion

        #region "Private Methods"


        private IDictionary<string, string> GetSampleMakes()
        {
            IDictionary<string, string> makes = new Dictionary<string, string>();

            makes.Add("1", "Acura");
            makes.Add("2", "Audi");
            makes.Add("3", "BMW");

            return makes;
        }

        private IDictionary<string, string> GetSampleModelsFromSelectedMake(string selectedMake)
        {
            IDictionary<string, string> models = new Dictionary<string, string>();

            switch (selectedMake)
            {
                case "1":
                    models.Add("1", "Integra");
                    models.Add("2", "RL");
                    models.Add("3", "TL");
                    break;
                case "2":
                    models.Add("4", "A4");
                    models.Add("5", "S4");
                    models.Add("6", "A6");
                    break;
                case "3":
                    models.Add("7", "3 series");
                    models.Add("8", "5 series");
                    models.Add("9", "7 series");
                    break;
                default:
                    throw new NotImplementedException();

            }

            return models;
        }


        private IDictionary<string, string> GetSampleColorsFromSelectedModel(string selectedModel)
        {
            IDictionary<string, string> colors = new Dictionary<string, string>();

            switch (selectedModel)
            {
                case "1":
                    colors.Add("1", "Green");
                    colors.Add("2", "Sea Green");
                    colors.Add("3", "Pale Green");
                    break;
                case "2":
                    colors.Add("4", "Red");
                    colors.Add("5", "Bright Red");
                    break;
                case "3":
                    colors.Add("6", "Teal");
                    colors.Add("7", "Dark Teal");
                    break;
                case "4":
                    colors.Add("8", "Azure");
                    colors.Add("9", "Light Azure");
                    colors.Add("10", "Dark Azure");
                    break;
                case "5":
                    colors.Add("11", "Silver");
                    colors.Add("12", "Metallic");
                    break;
                case "6":
                    colors.Add("13", "Cyan");
                    break;
                case "7":
                    colors.Add("14", "Blue");
                    colors.Add("15", "Sky Blue");
                    colors.Add("16", "Racing Blue");
                    break;
                case "8":
                    colors.Add("17", "Yellow");
                    colors.Add("18", "Red");
                    break;
                case "9":
                    colors.Add("17", "Brown");
                    break;
                default:
                    throw new NotImplementedException();

            }

            return colors;
        }

        #endregion

    }

View

@model CSDropdownListMVC4.Models.CascadingDropDownSampleModel

@{
    ViewBag.Title = "CascadingDropDown Demonstration in ASP.NET MVC 4";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section Scripts
{
    <script src="~/Scripts/CascadingDropDownSample.js"></script>
}


<table>
    <tr>
        <td>Marca</td>
        <td>
            <select id="make" class="size-200">
                <option value="-1">Selecione uma marca</option>
                @foreach (KeyValuePair<string, string> make in Model.Makes)
                {
                    <option value="@make.Key">@make.Value</option>
                }
            </select>
        </td>
    </tr>
    <tr>
        <td>Modelo</td>
        <td>
            <select id="model" class="size-200" disabled>
                <option value="-1">Selecione o modelo</option>
            </select>
        </td>
    </tr>
    <tr>
        <td>Cor</td>
        <td>
            <select id="color" class="size-200" disabled>
                <option value="-1">Selecione a cor</option>
            </select>
        </td>
    </tr>
</table>

Jquery

$(function () {
    var cascadingDropDownSample = new CascadingDropDownSample();

    $('#make').on('change', function () {
        var selectedMake = $(this).val();

        if (selectedMake !== "-1") {
            $.post('/CascadingDropDownSample/GetSampleModels',
                { selectedMake: selectedMake },
                function (data) {
                    cascadingDropDownSample.resetCascadingDropDowns();
                    cascadingDropDownSample.getSampleModelsSuccess(data);
                });
        }
        else {

            cascadingDropDownSample.resetCascadingDropDowns();
        }
    });

    $('#model').on('change', function () {
        var selectedModel = $(this).val();

        if (selectedModel !== "-1") {
            $.post('/CascadingDropDownSample/GetSampleColors',
                { selectedModel: selectedModel },
                function (data) {
                    cascadingDropDownSample.resetColors();
                    cascadingDropDownSample.getSampleColorsSuccess(data);
                });
        }
        else {
            cascadingDropDownSample.resetColors();
        }
    });
});

function CascadingDropDownSample() {
    this.resetCascadingDropDowns = function () {
        this.resetModels();
        this.resetColors();
    };

    this.getSampleModelsSuccess = function (data) {
        $.each(data, function (key, textValue) {
            $('#model').append($('<option />', { value: key, text: textValue }));
        });
        $('#model').attr('disabled', false);
    };

    this.getSampleColorsSuccess = function (data) {
        $.each(data, function (key, textValue) {
            $('#color').append($('<option />', { value: key, text: textValue }));
        });
        $('#color').attr('disabled', false);
    };

    this.resetModels = function () {
        $('#model option').remove();
        $('#model').append($('<option />', { value: '-1', text: 'Please select a model' }));
        $('#model').attr('disabled', 'disabled');
    };

    this.resetColors = function () {
        $('#color option').remove();
        $('#color').append($('<option />', { value: '-1', text: 'Please select a color' }));
        $('#color').attr('disabled', 'disabled');
    };
}

Reference https://code.msdn.microsoft.com/How-to-use-DropDownList-6ef6ffcb

0


Solved. I just created an empty list of cities and added it to Model and it worked.

did so.

Controller

public ActionResult add(){
            AddTaxModel model = new AddTaxModel();
            model.estados = new SelectList(new EstadoDAO().findAll(), "id", "nome");
            model.cidades = new SelectList(new List<Cidade>(), "id", "nome");                      
            return View(model);
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.