Set Value Default @Html.Dropdownlistfor via Json - ASP.NET MVC5

Asked

Viewed 146 times

0

I am making a timekeeping page using ASP.NET MVC5. The user enters the markup data as shown below: inserir a descrição da imagem aqui

However, if any error occurs in the registration of the tag, the controller returns the model to view with the data entered by the user, using the concept of Binding model, and already brings the fields filled by the user and the error message. As the print below:

inserir a descrição da imagem aqui

Note that I have brought all fields filled in, except for the official field. This Dropdownlist I fill via Json, it brings the dropdown filled with the employees, but it always comes selected the first item of the list, and not what user selected. My question is: How do I after I fill in @Html.Dropdownlistfor I set a specific value that will be displayed to the user.

The controller that returns Json with the Employee list is this:

  FuncionariosFiltro = (from ord in Funcionarios
                                                     join detail in listaTurnoFuncionario on ord.Id equals detail.TCAD_PLAN_TRAB_FUNCIONARIO.TCAD_FUNCIONARIOId
                                                     where detail.TCAD_PLAN_TRAB_FUNCIONARIO.DATA_INICIO <= DateTime.Now.Date && detail.TCAD_PLAN_TRAB_FUNCIONARIO.DATA_FIM >= Convert.ToDateTime(Session["DataAgenda"]).Date
                                                     && ord.CODIGO_STATUS.Id == 1 && (listaAusencia.Where(l => l.FUNCIONARIOId == ord.Id).Count()) == 0
                                                     select ord).ToList();

return Json(new SelectList(FuncionariosFiltro, "Id", "NOME"));

In the code below are the two Dropdownlist, the first of services, which when selected calls the controller above that returns the list of employees, which fills the second Dropdownlist, which is from Employees.

<div class="col-xs-8 col-sm-4 col-md-auto">
                @Html.DropDownListFor(p => p.CodigoServico, new SelectList(ViewBag.Servico, "CODIGO", "DESCRICAO"), "Serviço", new Dictionary<string, object>
                                                                                                                                {
                                                                                                                                    {"data-toggle", "tooltip"},
                                                                                                                                    {"title","Informe o serviço desejado"},
                                                                                                                                    {"class","form-control" },
                                                                                                                                    {"id","CategoryType" },
                                                                                                                                    {"name","CategoryType" }
                                                                                                                                })
            </div>

            <div class="col-xs-8 col-sm-4 col-md-auto">
                @Html.DropDownListFor(p => p.CodigoFuncionario, new SelectList(string.Empty, "Id", "NOME"),  new Dictionary<string, object>
                                                                                                                                {
                                                                                                                                    {"data-toggle", "tooltip"},
                                                                                                                                    {"title","Informe o Funcionário que irá realizar o serviço"},
                                                                                                                                    {"class","form-control" },
                                                                                                                                    {"id","SubCategory" },
                                                                                                                                    {"name","SubCategory" }
                                                                                                                                })

            </div>

When the user selects the service it triggers the Java Script below, which calls the controller that returns the employee list and fills the dropdownlist. I believe that this is the java script function that I should use to preselect the dropdownlist value, but I don’t know how to proceed.

$(document).ready(function () {

    $("#CategoryType").change(function () {

        $("#SubCategory").empty();

        $.ajax({

            type: 'POST',

            url: '@Url.Action("CarregarFuncionarioVSservico", "ManutencaoAgenda")',
            dataType: 'json',
            data: { id: $("#CategoryType").val() },
            success: function (subcategories) {

                $.each(subcategories, function (i, subcategory) {

                    $("#SubCategory").append('<option value="'
                        + subcategory.Value + '">' +
                        subcategory.Text + '</option>');
                });

            },
            error: function (ex) {
                alert('Failed to retrieve Sub Categories : ' + ex);
            }
        });
        return false;
    })
    });

1 answer

1


To set the Dropdownlist you have to inform that the record is selected. In the source below, change the regraParaSelecionar by its logic to validate the employee who was selected.

$.each(subcategories, function (i, subcategory) {
    if (regraParaSelecionar) {
        $("#SubCategory").append('<option selected="selected" value="' + subcategory.Value + '">' + subcategory.Text + '</option>');
    }
    else {  
        $("#SubCategory").append('<option value="' + subcategory.Value + '">' + subcategory.Text + '</option>');
    }
});     
  • I used the code sent, and it was exactly what I needed. Thank you so much for your help.

  • @Wagnerbarbosisif you manage to mark the answer as the answer to the question

Browser other questions tagged

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