I'm doing a time-stamping page using ASP.NET MVC5. The user enters the marking data according to the print below:
However,incaseofanerrorintheregistrationofthetag,thecontrollerreturnsthemodeltoviewwiththedataenteredbytheuser,usingtheconceptofmodelbinding,andalreadybringsthefieldsfilledbytheuserandtheerrormessage.Astheprintbelow:
Pleasenotethatyouhavefilledallfields,butlesstheemployeefield.ThisDropDownListIfillinviaJson,itbringsthedropdownfilledwithemployees,howeveritalwayscomesselectedthefirstiteminthelist,notwhatuserselected.Myquestionis:HowdoIafterfillinginthe@Html.DropDownListForIsetaspecificvaluethatwillbedisplayedtotheuser.
ThecontrollerthatreturnsJSonwiththelistofEmployeesisthis:
FuncionariosFiltro=(fromordinFuncionariosjoindetailinlistaTurnoFuncionarioonord.Idequalsdetail.TCAD_PLAN_TRAB_FUNCIONARIO.TCAD_FUNCIONARIOIdwheredetail.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 service, which when selected calls the above controller that returns the list of employees, which fills the second DropDownList, which is the 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 service is selected by the user it triggers the Java Script Below, which calls the controller that returns the list of employees and populates the dropDownList. I believe that it is in this function java script that I must move to pre-select the value of dropDownList, but I do not know which way 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;
})
});