javascript - 如何将JSON对象列表发送到灯箱?

标签 javascript ajax asp.net-mvc json lightbox

在 MVC 4 应用程序中,我希望单击链接时在灯箱中显示一些相关产品列表。我有方法返回我需要的产品:

 public ActionResult GetRelatedProducts(int id)
    {
       var realProducts = GetRelatedProducts(id);
       List<object> productsObjectList = new List<object>();
       foreach (var item in realProducts)
       {
             productsObjectList .Add(new
             {
                 id = item.Id,
                 fullname = item.Name
             });
       }
       return Json(productsObjectList , JsonRequestBehavior.AllowGet);
    }

HTML 是:

<a class="show" id="show">Show</a>

<div  id="productBox" style="display: none;">
    // Product list will get here
</div>

和脚本:

     $('#show').click(function (e) {
     url = '@Url.Action("GetRelatedProducts", "Product")';
     var data = { id: '@Model.Id' };
     $.post(url, data, function (result) {
           $('#productBox').lightbox_me({
           onLoad: function () {

             //How to send returned product list to light box, to show them by foreach loop

           }
       });
      e.preventDefault();
  });
});

如何将产品列表发送到 productBox 以展示产品?

最佳答案

您的代码:

$('#show').click(function (e) {
     url = '@Url.Action("GetRelatedProducts", "Product")';
     var data = { id: '@Model.Id' };
     $.post(url, data, function (result) { // <- "result" will contain array
       $('#productBox').lightbox_me({
           onLoad: function () { ... }
       });
       e.preventDefault(); // <- this must prevent "a" tag, put it outside
     });
});

您可以像这样在客户端使用您的列表:

$.post(url, data, function (result) {
    var list = '<ul>';
    for(var i = 0; i < result.length; i++)
    {
        list += '<li>' + result[i].fullname + '</li>';
    }
    list += '</ul>';
    $('#productBox').html(list).lightbox_me();
});

或者如Vladimir Bozic所写,只需使用PartialViewResult,从 Controller 返回PartialView,它就像普通 View ,但没有布局,只是html block ,你可以像这样使用它:

$.post(url, data, function (result) {
    $('#productBox').html(result).lightbox_me();
});

关于javascript - 如何将JSON对象列表发送到灯箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15025433/

相关文章:

c# - 是否可以通过Ajax上传文件?

javascript - 如何使 javascript 对象被视为虚假对象?

javascript - 您能推荐任何在线 JSON 网格查看器或表格查看器吗?

javascript - 在 Kiosk 模式下检测 Google Chrome

php - 数据表警告 : table id=dataTables - Ajax error. 404 未找到

c# - 启用 ASP.NET Web Api 以容纳 JSON 和表单编码数据

javascript - window.open 在字符串内不起作用

java - 使用 Tapestry 的 Bootstrap 模式内的 Ajax 区域形式

javascript - 通过 jQuery AJAX 和 keyup 事件搜索特定术语

c# - 无法转换为 LINQ to Entities 存储表达式