Problem with dropdownlist auto-refilling

Asked

Viewed 37 times

0

I’m having a small problem with the dropdownlist of Asp mvc 5, I need to automatically fill the value of the dropdownlist as soon as the user enters the search screen, I was able to get the value in the database but in the part of auto fill that is giving problem.

Here will direct the user to Filter screen, referring to div that he marked:

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

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

public ActionResult FiltroQuestao(string section)
    {

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

Now in the view I am using jquery to fill 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 popular power 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 Material, but I want it to come with the value of the bank, which in the example is Physics

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>');
        });
    }
});

});

  • It worked but the only problem is if the user enters the direct URL without passing parameter,la in json I did an IF if this situation occurred,with this change he also removes the <option>Select Subject</option> in both cases (I don’t know if I was very clear)

Browser other questions tagged

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