如何在mvc视图中使用jquery实现ajax弹出窗口?

时间:2021-11-16 13:29:47

Suppose I have a view to display the list of employee like:

假设我有一个显示员工列表的视图:

<table>
<% foreach (var item in Model)
{ %>
<tr><td>
 <img name=<%="disp"+item.id%> alt="" src="../../Content/Disp.gif" />
</td></tr>
<% { %>

Then I want to set mouseover and mouseout event for the image to disp the employee info in a popup box. If the mouse is over the image, display employee info in the box. If the mouse is out of the image, close the info box.

然后我想为图像设置mouseover和mouseout事件,以便在弹出框中显示员工信息。如果鼠标位于图像上方,则在框中显示员工信息。如果鼠标不在图像中,请关闭信息框。

Then I create controller action for ajax call to get employee data from database like:

然后我为ajax调用创建控制器操作以从数据库获取员工数据,如:

public ActionResult AjaxDisp(int id, string format)
{
  var obj= repository.GetEmployee(id);
  if (format == "json")
     return Json(obj);

  return View(obj);
}

Then I need to write some jquery code for mouseover event to get the data from the action and code for mouseout to close popup box if it is showing on.

然后我需要为mouseover事件编写一些jquery代码来获取动作中的数据和mouseout的代码以关闭弹出框(如果它正在显示)。

How to resolve this issue?

如何解决这个问题?

1 个解决方案

#1


You probably want to use the hover() method. It includes callbacks for over/out so that you can do different actions on over vs. out.

您可能想要使用hover()方法。它包括过/退的回调,以便您可以对over over out执行不同的操作。

  $('image').hover(
      function() {

           var empId = $(this).attr('name').replace(/disp/,'');
           $.ajax({
              url: '<%= Url.Action( "AjaxDisp" ) %>',
              data: { id: empId, format: 'json' },
              dataType: 'json',
              success: function(data,status) {
                 // populate the popup and display it            
              }
           });
      }
      function() {
           // remove (hide?) the popup
      }
  );

Note that you may want to cache the results of the AJAX query so you're not going back to the server every time you hover over the image.

请注意,您可能希望缓存AJAX查询的结果,这样每次将鼠标悬停在图像上时都不会返回服务器。

#1


You probably want to use the hover() method. It includes callbacks for over/out so that you can do different actions on over vs. out.

您可能想要使用hover()方法。它包括过/退的回调,以便您可以对over over out执行不同的操作。

  $('image').hover(
      function() {

           var empId = $(this).attr('name').replace(/disp/,'');
           $.ajax({
              url: '<%= Url.Action( "AjaxDisp" ) %>',
              data: { id: empId, format: 'json' },
              dataType: 'json',
              success: function(data,status) {
                 // populate the popup and display it            
              }
           });
      }
      function() {
           // remove (hide?) the popup
      }
  );

Note that you may want to cache the results of the AJAX query so you're not going back to the server every time you hover over the image.

请注意,您可能希望缓存AJAX查询的结果,这样每次将鼠标悬停在图像上时都不会返回服务器。