0

在 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来展示产品?

4

1 回答 1

2

你编码:

$('#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, from controller return PartialView,它就像普通视图,但没有布局,只是 html 块,你可以像这样使用它:

$.post(url, data, function (result) {
    $('#productBox').html(result).lightbox_me();
});
于 2013-02-22T14:12:58.237 回答