如何循环从控制器返回的json对象?

时间:2018-06-06 10:34:42

标签: c# json asp.net-mvc razor

我将JSON结果返回给控制器的视图。我想在RAZOR中循环它

[HttpGet]
public JsonResult Index()
{
    return Json(GalleryRepository.getImages(), JsonRequestBehavior.AllowGet);
}

在视图中:

@model ZahidCarWash.ViewModels.GetImagesViewModel
    @{
        foreach(var i in )
     }

getimages功能:

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;
    }

我想遍历要返回的值。

1 个答案:

答案 0 :(得分:0)

将控制器操作更改为:

[HttpGet]
public IActionResult Index()
{
    return View(GalleryRepository.getImages());
}

并将您的观点更改为以下内容:

@model List<ZahidCarWash.ViewModels.GetImagesViewModel>
@{
    foreach(var i in Model)
    {
       //do something with the image  
    }
 }