在 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/