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

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

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

调用模态的按钮:

  

模态的Html:

 @model Application.Models.ApplicationviewModels.StoreIndexData @using Application.Models 
@await Html.PartialAsync("_ModalHeader", new ModalHeader { Heading = String.Format("Actualización de Modelo: Tiendas") })

GET方法:

  public IActionResult Create(int? id) { List DepartmentList = new List(); 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 ListofDistrict = new List(); ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" }); ViewBag.ListofDistrict = ListofDistrict; return PartialView("~/Views/Shared/Stores/_Create.cshtml"); } 

问题:

我有以下jQuery,一旦模态打开,它就会向ZoneID赋值:

  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 = "-- Seleccione Distrito --"; $('#DistrictID').html(items); }; }); });  

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

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

这条线丢了:

 var items = "-- Seleccione Distrito --"; 

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

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

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

在此处输入图像描述

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

第2部分 – 第1部分:我们第二次打开模态

在此处输入图像描述

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

第2部分 – 第2部分:分配jQuery的值时

在此处输入图像描述

  • 来自jQuery的值被分配给DistrictID
  • 该值将被GET操作的结果覆盖

题:

谁能解释或帮助我理解可能导致这种情况的原因? 我还能做些什么来找出背后的原因?

尝试将html的分配从主视图移动到zoneID到mod.popUp视图的document.ready

  @model Application.Models.ApplicationviewModels.StoreIndexData @using Application.Models 
@await Html.PartialAsync("_ModalHeader", new ModalHeader { Heading = String.Format("Actualización de Modelo: Tiendas") })

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

 

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

 $('#modal-action-store').on('show.bs.modal', function(e){ var items = ""; $('#DistrictID').html(items); }); 
      

我会更新您的http://plataformafantasypark.azurewebsites.net/Stores/create以包含默认情况下。 这将限制用零条目覆盖元素的选项。 这将使您的js代码更容易。

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