简体   繁体   English

如何遍历从控制器返回的json对象?

[英]How do I loop through the json object returned from the controller?

I am returning JSON result to the view from controller. 我将JSON结果从控制器返回到视图。 I want to loop through it in RAZOR 我想在RAZOR中循环浏览

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

in view: 鉴于:

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

getimages function: 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;
    }

I want to loop through the values that are being returned. 我想遍历正在返回的值。

Change your controller Action to this: 将您的控制器操作更改为:

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

and change your view to something like this: 并将您的视图更改为以下形式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM