0

I have a list of image urls that I am trying to display. I am passing the list from the controller to the view. I know that the list is being created successfully. But when it gets to the view, javascript interprets it as "*System.Collections.Generic.List1[System.String]*`" not as the actual list. This causes the images not to be displayed.

Here is the line of code that I am using to assign the list to js variable:

var imageUrls = '@Model.PicUrls';

and the controller

public ActionResult Index()
    {
        var pics = _ctx.Image.Select(m => m).Take(10).ToList<ImageModel>();

        var picUrls = new List<string>();

        for (int i = 0; i <= pics.Count - 1; i++)
        {
            picUrls.Add(pics[i].ImageUrl);

        }

        var outModel = new ViewPostViewModel
        {
            PicUrls = picUrls
        };

        return View(outModel);

I tried to return a Json object but then the page literally only displayed was the completed list.

return Json(outModel.PicUrls, JsonRequestBehavior.AllowGet);

So, the Json advice worked somewhat but it is not quite there

4

2 回答 2

0

得到

System.Collections.Generic.List`1[System.String]

因为你是模型值 PicUrls 默认 ToString() 实现是返回它的类型。

您可以将 PicUrls 存储为 JSON 字符串,然后解析为 js 中的 javascript 数组。

公共 ActionResult Index() { var pics = _ctx.Image.Select(m => m).Take(10).ToList();

    var picUrls = String.Empty;

    for (int i = 0; i <= pics.Count - 1; i++)
    {
        picUrls += (picUrls != String.Empty ? ", " : "") + @"""" + pics[i].ImageUrl + @"""";
    }

    var outModel = new ViewPostViewModel
    {
        PicUrls = @"[" + picUrls + "]";
    };

    return View(outModel);

在你的 js 中,使用

var imageUrls = JSON.parse('@Model.PicUrls');
于 2013-06-07T05:10:56.653 回答
0

试试看

  public ActionResult Index()
    {
        var pics = _ctx.Image.Select(m => m.ImageUrl)
        .Take(10).ToList();

        var picUrls = new List();

        for (int i = 0; i <= pics.Count - 1; i++)
        {
            picUrls.Add(pics[i]);

        }

        var outModel = new ViewPostViewModel
        {
            PicUrls = picUrls
        };
return Json(outModel.PicUrls, JsonRequestBehavior.AllowGet);
}
于 2013-06-07T05:14:47.277 回答