将值从视图传递到另一个视图

时间:2019-02-11 20:14:23

标签: jquery ajax asp.net-mvc

我有一个MVC应用程序,它想要在Controller视图之一上隐藏和显示div。

所以我有一个父视图,

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>

和一个js代码,

$(document).ready(function () {
$.ajax({
    type: 'GET',
    url : '@Url.Action(actionName: "Action1", controllerName: "Controller1")',
    dataType: "html",
    async:true,
    success: function (result) { $("#div1").html(result); }
    });
$.ajax({
    type: 'GET',
    url : '@Url.Action(actionName: "Action2", controllerName: "Controller2")',
    dataType: "html",
    async:true,
    success: function (result) { $("#div2").html(result); }
    });

$.ajax({
    type: 'GET',
    url : '@Url.Action(actionName: "Action3", controllerName: "Controller3")',
    dataType: "html",
    async:true,
    success: function (result) { $("#div3").html(result); }
    });

});

这将使用控制器视图加载div。但是我想一次显示一个div。每个div停留10秒。 还有一种更好的方法来编写$(document).ready(function()吗? 预先感谢

1 个答案:

答案 0 :(得分:0)

$(function() {
  var divs = $(".myDiv");
  var sampleImageList = ["animals", "arch", "nature"];

  // make your ajax calls and insert it into respective div
  var request = function(action, controller, div) {
    var url = "@Url.Action(actionName: " + action + "," + "controllerName: " + controller + ")";
    var index = $(divs).index(div);
    var sampleImage = "<img src=\"https://placeimg.com/640/480/" + sampleImageList[index] + "\">";
    $(div).html(sampleImage);

    /* use ur Ajax call  
    $.ajax({
        type: 'GET',
        url: url,
        dataType: "html",
        success: function(result) {
          $(div).html(result);
        },
        error: function(xhr, status) {
          $(div).html(status); // handle error here 
        }
      }); */

  };

  var swap = function() {
    var $active = $("#myGallery .active");
    var $next = ($("#myGallery .active").next().length > 0) ? $("#myGallery .active").next() : $("#myGallery div:first");

    $active.fadeOut(function() {
      $active.removeClass("active");
      $next.fadeIn().addClass("active");
    });
  }; // swap end

  divs.each(function(index, div) {
    var action = $(div).attr("data-action");
    var controller = $(div).attr("data-controller");
    request(action, controller, div);
  }); // divs end
  
  $("#myGallery .active").fadeIn(); // show first div
  setInterval(swap, 10000);

});
#myGallery .myDiv{
  display : none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="myGallery">
  <div id="div1" class="myDiv active" data-action="first" data-controller="home"> </div>
  <div id="div2" class="myDiv" data-action="second" data-controller="home"></div>
  <div id="div3" class="myDiv" data-action="third" data-controller="home"></div>
</div>
我们使用CSS隐藏所有div。 立即,我们将发出所有AJAX请求并将其保存到相应的div中。然后,我们使用交换功能显示或隐藏div。如果发生AJAX错误,您可以附加一个占位符图像或显示错误消息,这取决于您。

https://jsfiddle.net/r958njhq/