Estou com um problema pra carregar os campos select no meu projeto. Meus forms estão todos feitos com Razor e apenas os select's(combobox) eu carrego por ajax.
Problema: Quando inicio o formulário é iniciado o evento ajax para carregar os combos é disparado antes de eu obter os dados do meu model, cujo precisava para obter o ID pro campo ficar com o valor certo já selecionado.
Alguém saberia qual a solução para este caso? Como consigo iniciar ou obter o valor do meu model antes do evento ser disparado? Ah e Também acho q pode ser relevante o fato do meu form esta em uma 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>
}
$(document).ready(function() { .... });
, mas, internamente seu Script ta com problemas! – novic 21/03/18 às 14:16$(document).ready(function() { getListaResponsavelLegal() });
tente assim retirando aquela linha sozinhagetListaResponsavelLegal()
e ve se funciona? – novic 21/03/18 às 14:31