jQuery:与在不适当的时间执行的removeData()冲突

时间:2017-12-02 16:31:32

标签: javascript jquery twitter-bootstrap asp.net-core-mvc

我有一个模态窗口,用于更新或添加新对象Store

远程调用此模式,从ASP.NET中构造的GET方法加载信息。

调用模式的按钮:

<div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create" 
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>

模式的Html:

@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

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

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">Distrito</label>
                <div class="col-md-10">
                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                </div>
            </div>
            {... more elements}
       </div>
</form>

GET方法:

    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }

问题:

我有以下jQuery,一旦模态打开,它就会将值赋给DistrictID

<script type="text/javascript">

    var wasclicked = 0;
    var $this = this;

    $(document).ready(function () {

        document.getElementById("modalbutton").onclick = function () {
            //is AddNew Store button is hitted, this var = 1
            wasclicked = 1;
        };

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

        $('#modal-action-store').on('shown.bs.modal', function (e) {
            console.log($('#DistrictID').length);
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            };
        });
    });
</script>

现在的问题是,在执行此行jQuery后,分配给DistrictID的值将被覆盖:

  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"

这条线丢失了:

var items = "<option value='0'>-- Seleccione Distrito --</option>";

我怀疑来自控制器的信息会覆盖模式中jQuery的任何结果。

经过调试后,我发现了三个不同的时刻:

时刻1:我们第一次打开模态

enter image description here

  • 模态还没有打开,jQuery执行
  • 因此,它无法识别DistrictID
  • GET Action的结果填充了模态的输入。

时刻2 - 第1部分:我们第二次打开模态

enter image description here

  • 这次模式在执行jQuery之前打开
  • 在我们从jQuery
  • 分配值之前,DistrictID具有GET方法的值

时刻2 - 第2部分:分配jQuery的值时

enter image description here

  • jQuery的值已分配给DistrictID
  • 此值将被GET操作
  • 的结果覆盖

问题:

任何人都可以解释或帮助我理解可能导致此问题的原因吗?我还能做些什么来找出背后的原因?

3 个答案:

答案 0 :(得分:1)

尝试将html的分配从主视图移动到districtID到模态弹出视图的document.ready

    @model Application.Models.ApplicationviewModels.StoreIndexData
    @using Application.Models

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

            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="modal-body form-horizontal">
                <div class="form-group">
                    <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                    <div class="col-md-10">
                        <select asp-for="DepartmentID" class="form-control"
                                asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">Distrito</label>
                    <div class="col-md-10">
                        <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                                asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                    </div>
                </div>
                {... more elements}
           </div>
    </form>

<script type="text/javascript">

    $(document).ready(function () {
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            }
    });

</script>

PS:也可以使用默认选项。请参考以下代码。

<div class="form-group">
 <label class="col-md-2 control-label">Distrito</label>
  <div class="col-md-10">
   <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
     <option value='0'>-- Seleccione Distrito --</option>
  </select>
 </div>
</div>

答案 1 :(得分:0)

modal()只接受选项对象或字符串。要将元素附加到模态,我们可以在触发show.bs.modal时附加它们:

&#13;
&#13;
$('#modal-action-store').on('show.bs.modal', function(e){
	var items = "<option value='0'>-- Seleccione Distrito --</option>";
    $('#DistrictID').html(items);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create" 
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
<div class="modal" id="modal-action-store">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <select class="form-control" id="DistrictID" name="DistrictID">
        </select>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

默认情况下,我会将您的http://plataformafantasypark.azurewebsites.net/Stores/create更新为包含<option value='0'>-- Seleccione Distrito --</option>。这将限制用零条目覆盖元素的选项。 这将使您的js代码更容易。

顺便说一句,为什么在使用document.getElementById("modalbutton").onclick时可以使用$("#modalbutton").on("click", function(){});,因为你正在使用jQuery。