Auto-fill dropdownlist problem

0

I am having a small problem with the asp mvc 5 dropdownList, I need to automatically populate the dropdownlist value as soon as the user enters the search screen, I have already been able to get the value in the database but in the autofill part that it is giving problem.

Here you will direct the user to the Filter screen, referring to the div he tagged:

<a href="@Url.Action("FiltroQuestao", "Quiz", new { section = "Fisica"})">Questões</a>

Here you will recover the value of the section to be able to buy with the bank

public ActionResult FiltroQuestao(string section)
    {

        TempData["Materia"] = section;
        return View();
    }

Now in the view I'm using jquery to populate the dropdownlist

  $(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "/Quiz/GetState",
        datatype: "Json",
        success: function (data) {
            $.each(data, function (index, value) {
                $('#ddlState').append('<option value="' + value.idMateria + '">' + value.nomeMateria + '</option>');
            });
        }
    });
});

In this part I'm using json to be able to dropdownlist via ajax

 public JsonResult GetState()
    {
        var valorMateria = TempData["Materia"];
        if(valorMateria != null)
        {
            var stateData = db.Materia.Where(x => x.nomeMateria == valorMateria.ToString()).ToList();
            return Json(stateData, JsonRequestBehavior.AllowGet);
        }
        var stateData2 = db.Materia.ToList();
        return Json(stateData2, JsonRequestBehavior.AllowGet);
    }

This is the dropdownlist

  @Html.DropDownList("ddlState", new SelectList(string.Empty, "Value", "Text"), "Selecionar Materia", new { @class = "form-control" })

By default it is coming as Select Matter, but I want it to come with the value that is from the bank, which in the example is Physical

    
asked by anonymous 11.01.2018 / 03:32

1 answer

1

It turns out that on the return of your Get, you simply add the result of the Query and the <option>Selecionar Matéria</option> is already there.

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "/Quiz/GetState",
        datatype: "Json",
        success: function (data) {         

       //Removendo os options existentes
       $('#ddlState').find('option').remove();

        $.each(data, function (index, value) {
            $('#ddlState').append('<option value="' + value.idMateria + '">' + value.nomeMateria + '</option>');
        });
    }
});

});

    
11.01.2018 / 16:51