延迟执行Javascript

时间:2017-09-15 18:31:58

标签: javascript c# jquery asp.net ajax

在我的项目中,我有一个模态窗口,其中显示了类(Family)的两个属性(TypeIDMachine)的级联下拉列表

问题: 仅当模态窗口第二次打开时,依赖下拉列表才会填充。第一次,没有任何事情发生:

这是一张如何更好地理解它的图片:

enter image description here

请注意, Modelo (Modelo是TypeID的名称)的行在第一时间为空,但重新打开后,会填充预期的信息。< / p>

代码:

注意 Javascript位于索引页面中,其中包含指向模态窗口的链接

创建或编辑新Machine时使用此模态窗口。 出于这个原因,在Javascript的第一部分,我检查我的情况,并检查Machine属性:MchName是否有值。 如果它没有值,我将变量items的值分配给在模态打开时应显示的属性TypeID

@section scripts{
<script src="~/js/machine-index.js" asp-append-version="true"></script>


<script type="text/javascript">
    $(document).ready(function () {
        $('#FamilyID').change(function () {
            var url = '@Url.Content("~/")' + "Machines/GetModel";
            var ddlsource = "#FamilyID";
            $.getJSON(url, { FamilyID: $(ddlsource).val() }, function (data) {
                var items = '';
                $("#TypeID").empty();
                $.each(data, function (i, model) {
                    items += "<option value='" + model.value + "'>" + model.text + "</option>";
                });
                $('#TypeID').html(items);
            });
        });
        $('#modal-action-machine').on('shown.bs.modal', function () {
            var test = "#MchName";
            if ($(test).val()) {

            } else {
                var items = "<option value='0'>-- Seleccione Modelo --</option>";
                $('#TypeID').html(items);
            }
        });
    });
</script>
<script type="text/javascript">
    $(function () {
        $('.datepicker').datepicker({
            "autoclose": true,
            format: 'dd/mm/yyyy'
        }).datepicker("setDate", new Date());
    });
</script>
<script src="~/lib/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
}

获取方法:

    [HttpGet]
    public IActionResult CreateEdit(int? id)
    {
        //Lista de Familias
        List<MachineFamily> FamilyList = new List<MachineFamily>();
        FamilyList = (from family in _context.MachineFamilies
                      select family).ToList();
        FamilyList.Insert(0, new MachineFamily { FamilyID = 0, FamilyDescription = "-- Seleccione Familia --" });
        ViewBag.ListofFamily = FamilyList;

        ViewBag.TypeID = string.Empty;
        return PartialView("~/Views/Shared/Machines/_Create.cshtml");
    }

JsonResult:

    public JsonResult GetModel(int FamilyID)
    {
        List<MachineType> ListaModelos = new List<MachineType>();
        ListaModelos = (from model in _context.MachineTypes
                        where model.FamilyID == FamilyID
                        select model).ToList();
        ListaModelos.Insert(0, new MachineType { TypeID = 0, TypeDescription = "-- Seleccione Modelo --" });
        return Json(new SelectList(ListaModelos, "TypeID", "TypeDescription"));
    }

查看:模态

@model Application.Models.ApplicationviewModels.MachineIndexData
@using Application.Models

<form asp-action="CreateEdit" role="form">
    @await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo") })

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="modal-body form-horizontal">
        <input type="hidden" asp-for="Id" />
        <div class="form-group">
            <label asp-for="FamilyID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="FamilyID" class="form-control"
                        asp-items="@(new SelectList(ViewBag.ListofFamily,"FamilyID","FamilyDescription"))"></select>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="TypeID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="TypeID" class="form-control"
                        asp-items="@(new SelectList(ViewBag.TypeID,"TypeID","TypeDescription"))"></select>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="BrandID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="BrandID" class="form-control" asp-items="ViewBag.BrandID">
                    <option value="">-- Seleccione Marca --</option>
                </select>
                <span asp-validation-for="BrandID" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="SupplierID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="SupplierID" class="form-control" asp-items="ViewBag.SupplierID">
                    <option value="">-- Seleccione Proveedor --</option>
                </select>
                <span asp-validation-for="SupplierID" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="StoreID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="StoreID" class="form-control" asp-items="ViewBag.StoreID">
                    <option value="">-- Seleccione Tienda --</option>
                </select>
                <span asp-validation-for="StoreID" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="MchName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="MchName" class="form-control" />
                <span asp-validation-for="MchName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="NumDevices" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input id="NumDevices" asp-for="NumDevices" class="form-control" readonly />
                <span asp-validation-for="NumDevices"  class="text-danger"></span>
                <input id="getNum" type="range" min="" max="10" step="1" onchange="fetch()" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="FechaCompra" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input data-format="0:dd/MM/yyyy" type="datetime" asp-for="FechaCompra" class="form-control datepicker" />
                <span asp-validation-for="FechaCompra" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="CostoMaq" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="CostoMaq" class="form-control" />
                <span asp-validation-for="CostoMaq" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="MachineStatus" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select name="MachineStatus" asp-for="MachineStatus" class="form-control" disabled>
                    <option value="0">Operativo</option>
                    <option value="1" selected="selected">Nuevo Item</option>
                    <option value="2">Reparación</option>
                </select>
                <input type="hidden" name="MachineStatus" value="1" />
                <span asp-validation-for="MachineStatus" class="text-danger"></span>
            </div>
        </div>

        @await Html.PartialAsync("_ModalFooter", new ModalFooter { })
    </div>
</form>

最后的说明:我相信要解决这个问题,我应该更改Javascript。有人可以向我解释为什么会发生这种情况以及如何解决它?

更新:尝试将新ID分配给'MKName'字段并将其发送到脚本

查看:

    <div class="form-group">
        <label asp-for="MchName" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input id="MchName2" asp-for="MchName" class="form-control" />
            <span asp-validation-for="MchName" class="text-danger"></span>
        </div>
    </div>

脚本:

        $('#modal-action-machine').on('shown.bs.modal', function () {
            var test = document.getElementById("MchName2").value;
            if (test) {

            } else {
                var items = "<option value='0'>-- Seleccione Modelo --</option>";
                $('#TypeID').html(items);
            }
        });

没有运气。

更新:第二次尝试

查看:

    <div class="form-group">
        <label asp-for="MchName" class="col-md-2 control-label"></label>
        <div class="col-md-10" id="MchName2">
            <input asp-for="MchName" class="form-control" />
            <span asp-validation-for="MchName" class="text-danger"></span>
        </div>
    </div>

脚本:

        $('#modal-action-machine').on('shown.bs.modal', function () {
            var test = "#MchName2 #MchName";
            if ($(test).val()) {

            } else {
                var items = "<option value='0'>-- Seleccione Modelo --</option>";
                $('#TypeID').html(items);
            }
        });

2 个答案:

答案 0 :(得分:2)

您应该将shown.bs.modal个事件处理程序包装在一个document.ready函数中。

每次触发shown.bs.modal事件时,它都会将change事件处理程序绑定到您的select元素。你应该只bind一次。

script type="text/javascript">
$(document).ready(function () {
    $('#FamilyID').change(function () {
        var url = '@Url.Content("~/")' + "Machines/GetModel";
        var ddlsource = "#FamilyID";
        $.getJSON(url, { FamilyID: $(ddlsource).val() }, function (data) {
            var items = '';
            $("#TypeID").empty();
            $.each(data, function (i, model) {
                items += "<option value='" + model.value + "'>" + model.text + "</option>";
            });
            $('#TypeID').html(items);
        });
    });
    $('#modal-action-machine').on('shown.bs.modal', function () {
        var test = "#MchName";
        if ($(test).val()) {

        } else {
            var items = "<option value='0'>Select</option>";
            $('#TypeID').html(items);
        }
    });
});

答案 1 :(得分:0)

我找到了一个适用于这个具体案例的答案。

第一个错误的是评估未在if语句中定义的变量。

$('#modal-action-machine').on('shown.bs.modal', function () {
    var test = "#MchName";
    if ($(test).val()) {

在此代码中,我将#MchName的值分配给test,但在第一时间,#MchName在第一次打开模态之前未定义,并且为此,而不是执行其余的代码。

第二:转身是使用Create按钮的点击事件来确定我是在新机器还是仅更新。

为此我将声明一个全局变量并为其赋值零。 如果单击“创建”按钮,则为此变量指定值1,如果为true,则指定用于#TypeID变量的默认值。

模态关闭后,将全局变量重新设置为零。这样,对于另一个按钮(更新)被命中以调用模态的情况。

这是代码:

var global = this;
var wasclicked = 0;

$(document).ready(function () {

    document.getElementById("modalbutton").onclick = function () {
        global.wasclicked = 1;
    };

    $('#modal-action-machine').on('hidden.bs.modal', function () {
        global.wasclicked = 0;
    });

    $('#modal-action-machine').on('shown.bs.modal', function () {
        if (global.wasclicked == 1) {
            var items = "<option value='0'>-- Seleccione Modelo --</option>";
            $('#TypeID').html(items);
        }

    });

通过这个,项目按预期工作。

感谢您的帮助!