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>
}