Ajax in MVC - Select

Asked

Viewed 329 times

1

I’m having a problem loading the fields select in my project. Mine Forms are all done with Razor and only the select’s(combobox) I charge by ajax.

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

Would anyone know the solution to this case? How can I start or get the value of my model before the event is triggered? Ah and I also think it may be relevant the fact of 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>
}
  • Show your code or a minimal example!?

  • I added the code. @Virgilionovic

  • Your code missed a similar call $(document).ready(function() { .... });, but, internally your script ta with problems!

  • What kind of problem? like I know I need to pass the model value on the date of my ajax, other than that there is some other problem? I do not master javascript know only the basics. I hope you can help me.

  • $(document).ready(function() { getListaResponsavelLegal() }); try so removing that line alone getListaResponsavelLegal() and see if it works?

  • still when you are running Function my model still null

  • is what I’m saying ... is wrong your code

  • Ops do not know if it is relevant, but the form in use is in a Partialview.

  • Yeah, but what’s wrong? @Virgilionovic

Show 4 more comments

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 question as to this, open the Developer Tools -> Network and see if the request returns a code 200 and the JSON expected in the Response.

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

In your specific case, the most prudent thing to do is to @RenderSection("scripts", false) in your file of Layout towards the end of body. Follow 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 file *.js and add the attribute defer to tag script

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

As the last change, add the event readystatechange at the document and hope that the document crash interactive to execute the 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 the jQuery.ready.

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

$(getListaResponsavelLegal)

Browser other questions tagged

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