"Filter" options of a DropDownList based on a selected option from another DropDownList

0

Greetings from Stack Overflow!

I have a cruel question on Javascript/Jquery that is consuming me longer than I would like (heh!) - I would like to filter a Dropdownlist based on the options of another Dropdownlist .

The image below represents more or less what I'm hoping to do!

Here'sthepartofHTMLthatdoesthis:

<divclass="form-group col-sm-3">
                <label>Nome do cadastro:</label>
                @Html.DropDownListFor(m => m.FinancialItems, new SelectList(Model.FinancialItems, "Description", "Description"),
                   new { @id = "nomeCadastro", @class = "form-control" })
            </div>

This class fetches the data directly from the database and populates it with a simple "toList ()".

I'm using Javascript , JQuery , and C# with MVC5 .

Is it possible to do this directly in JS/JQuery ? (If there is a API/Plugin that deals with this, it works!

Thank you !!!!!!!!!

    
asked by anonymous 04.01.2018 / 12:14

1 answer

0

After a lot of kicking, I managed to solve it!

I had to use a function in the Back End with a bit of JS:

function GetFinancialItems(_id) {
var procemessage;
var url = "/Financial/GetFinancialItemsById/";

if (_id != 0) {
    procemessage = "<option value='0'>Aguarde...</option>";
    $("#ddlfinancialitems").html(procemessage).show();

    $.ajax({
        url: url,
        data: { id: _id },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>Selecione</option>";

            if (data.length > 0) {
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }

                $("#ddlfinancialitems").prop("disabled", false);
                $("#ddlfinancialitems").html(markup).show();
            }
        },
        error: function (reponse) {
            alert("error : " + reponse);
        }
    });
} else {
    procemessage = "<option value='0'>Selecione o 'Tipo da Operação'</option>";
    $("#ddlfinancialitems").html(procemessage).show();
    $("#ddlfinancialitems").prop("disabled", true);
}

};

Along with a function in C # (with a post):

[HttpPost]
    public ActionResult GetFinancialItemsById(int id) {
        List<FinancialItem> iFinancialItems = new List<FinancialItem>();
        iFinancialItems = _DB.FinancialItem.Where(f => f.OperationId == id).ToList();
        SelectList iFinancialItemList = new SelectList(iFinancialItems, "Id", "Description", 0);
        return Json(iFinancialItemList);
    }

That solved! But I appreciate all the answers.

    
08.01.2018 / 12:05