views:

341

answers:

1

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.

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

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.

How to resolve this issue?

+3  A: 

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.

  $('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.

tvanfosson
Thanks. Could you give me in more detail? If use $('image'), it won't know the different for each image in each row. Image in different row should cause different employee data retrieve. How to pass the specific employee for each row for this case?
KentZhou
Looks like you are encoding the employee id in the name of the image. You could extract it from there. I've updated my example to show how to do this.
tvanfosson
Thanks again. I just tried your solution. But the ajax call not working. Action method was not called. Then I changed the call like url: '<%= Url.Action( "AjaxDisp" , "MyControllrt") %>',it is still not work. Any idea?
KentZhou
Figured it out: because of nullable param not matching. Thanks.
KentZhou
One more question: after ajax call, where to get the json result from the call? in your code success: function(data,status), what's data and status?
KentZhou
The data parameter should contain your JSON object.
tvanfosson