Ajax in MVC - Select

1

I have a problem loading the select fields in my project. My forms are all done with Razor and only the select's (combobox) I load by ajax.

Problem: When I start the form the ajax event to load the combos is triggered before I get the data from my model , which I needed to get the ID pro field get the right value already selected.

Would anyone know the solution to this case? How do I start or get the value of my model before the event is triggered? Oh and also I think it may be relevant that my form is in a PartialView.

@model EP.IdentityIsolation.Domain.Entities.Cadastro.Cliente
@{
    ViewBag.Title = "Cadastro de Cliente";
}

<div class="card-body excluir-padding-top">
    @using (Html.BeginForm("SalvarCliente", "Cliente", FormMethod.Post, new { id = "formCliente" }))
    {

    <div class="form-body">

        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.ResponsavelLegal, new { @class = "control-label" })
            <select class="form-control input-validation-error" id="ResponsavelLegal_Id" name="ResponsavelLegal.Id">
                <option value="null">Nenhum</option>
            </select>
            <small>@Html.ValidationMessageFor(model => model.ResponsavelLegal, "", new { @class = "text-danger" })</small>
        </div>

        <div class="form-group">
                @Html.LabelFor(model => model.RazaoSocial, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.RazaoSocial, new { htmlAttributes = new { @class = "form-control", autocomplete = "off" } })
                <small>@Html.ValidationMessageFor(model => model.RazaoSocial, "", new { @class = "text-danger" })</small>
            </div>

    </div>

    }
</div>

@section Scripts{

    <script type="text/javascript">

    getListaResponsavelLegal();
        function getListaResponsavelLegal() {
            var model = @Html.Raw((Model!= null && Model.ResponsavelLegal != 
            null) ? Model.ResponsavelLegal.Id : "");
            var ddlResponsavellegal = $("#ResponsavelLegal_Id");

            $.ajax({
                url: "DdlListaCliente",
                type: 'post',
                dataType: 'json',
                success: function (data) {

                    // Remover todos existentes;
                    ddlResponsavellegal.empty();

                    // Criar campo vazio;
                    var opt = new Option("Nenhum", null);
                    ddlResponsavellegal.append(opt);

                    // Carrega lista do retorno
                    for (var i = 0; i < data.length; i++) {
                        var opt = new Option(data[i].NomeFantasia, data[i].Id);
                        ddlResponsavellegal.append(opt);
                    }

                }
            });
        }

    </script>
}
    
asked by anonymous 21.03.2018 / 15:09

1 answer

2

I'm assuming that the Controller is being called and the data is being received in the correct way. If there is any doubt about this, open Developer Tools -> Network and see if the request returns a code 200 and JSON expected in Response .

The only reason an element is not accessible in Script, is that the script is running before page rendering.

In your specific case, the most prudent thing is to move the @RenderSection("scripts", false) in your file from Layout to the end of body . Here is an example:

<html>
    <head>
        /* estilos aqui */
        @RenderSection("scripts", false)
        /* scripts de blibiotecas aqui */
    </head>
    <body>
        /* corpo da pagina aqui */
        @RenderSection("scripts", false)
    </body>
</html>

A second option is to move the script in question to a *.js file and add the attribute defer to tag script

@section Scripts{
  <script type="text/javascript" src="*.js" defer>
}

As last change, add the event readystatechange to document and wait for document to be interactive to execute getListaResponsavelLegal .

var getListaResponsavelLegal = function () {
  /* faça a sua magina aqui */
}

document.addEventListener("readystatechange", function (evt) {
  if (document.readyState == "interactive") {
    getListaResponsavelLegal()
  }
})

You can achieve a similar effect with jQuery when using jQuery.ready .

var getListaResponsavelLegal = function () {
  /* faça a sua magina aqui */
}

$(getListaResponsavelLegal)
    
27.03.2018 / 15:22