c# - 如何循环从控制器返回的 json 对象?
问题描述
我正在从控制器将 JSON 结果返回到视图。我想在 RAZOR 中循环遍历它
[HttpGet]
public JsonResult Index()
{
return Json(GalleryRepository.getImages(), JsonRequestBehavior.AllowGet);
}
鉴于:
@model ZahidCarWash.ViewModels.GetImagesViewModel
@{
foreach(var i in )
}
获取图像功能:
public static List<GetImagesViewModel> getImages()
{
List<GetImagesViewModel> lstImages = new List<GetImagesViewModel>();
SqlConnection conn = null;
SqlCommand cmd = null;
try
{
string ConnectionString = Utility.getConnectionString();
conn = new SqlConnection(ConnectionString);
cmd = new SqlCommand("getImages", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter Adapter = new SqlDataAdapter(cmd);
conn.Open();
DataTable dt = new DataTable();
Adapter.Fill(dt);
conn.Close();
foreach (DataRow dr in dt.Rows)
{
GetImagesViewModel getImagesVM = new GetImagesViewModel();
getImagesVM.ID = Convert.ToInt16(dr["ID"]);
getImagesVM.Image = Convert.ToString(dr["Image"]);
lstImages.Add(getImagesVM);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Dispose();
cmd.Dispose();
}
return lstImages;
}
我想遍历正在返回的值。
解决方案
将您的控制器操作更改为:
[HttpGet]
public IActionResult Index()
{
return View(GalleryRepository.getImages());
}
并将您的视图更改为以下内容:
@model List<ZahidCarWash.ViewModels.GetImagesViewModel>
@{
foreach(var i in Model)
{
//do something with the image
}
}
推荐阅读
- javascript - 为什么highcharts上的第一个数据不像其他数据
- react-redux - 如何根据数据更新 state-React-redux 前后调用函数
- javascript - 尝试实现增量器
- bash - 使用 paramiko 与交互式 shell 调用时,shell 脚本的行为不同
- ios - 从一页到另一页的反应导航不起作用
- windows - 获取当前活动窗口的线程 ID
- sql - django.db.utils.NotSupportedError: FOR UPDATE 不能应用于外连接的可空端
- jspdf - 仅在 jspdf-autotable 3.1.1 中的第一页显示头部
- python - 估计的自由度不足
- mysql - 如何查找未出版书籍的作者数量