将字符串传递为JSON格式并自动编码

时间:2014-07-07 12:43:51

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

我想将json字符串传递给Javascript函数,并动态生成JSON。但是在函数中传递了JSON参数后,它会用“e;”双引号编码。 我正在使用C#MVC 4.0 这是我的代码: -

string strAllImages = "[";

foreach (var images in Model.PostsImageList)
{    
     if (strAllImages.Trim() != "[")
     {
         strAllImages = strAllImages + ",";
     }
     strAllImages = strAllImages + "'~/postImages/" + images.Image_Post_URL + "'";            

}   

strAllImages = strAllImages + "]";

<script language="javascript" type="text/javascript">

$(document).ready(function(){ // on document load

    $("#thumbsliderdiv").imageSlider({ //initialize slider
        'thumbs': @strAllImages, 
        'auto_scroll':true,
        'auto_scroll_speed':4500,
        'stop_after': 2, //stop after x cycles? Set to 0 to disable.
        'canvas_width':700,
        'canvas_height':500 // <-- No comma after last option
        })
});

</script>

1 个答案:

答案 0 :(得分:3)

您的代码中缺少什么使其立即起作用:

'thumbs': @Html.Raw(strAllImages)

但如果使用JSON.net,它会更干净。 G:

string [] strAllImagesAsArray = Model.PostsImageList.Select(i =>  "'~/postImages/" + i.Image_Post_URL + "'").ToArray() ; 

在你的javascript:

<script language="javascript" type="text/javascript">

$(document).ready(function(){ // on document load

    $("#thumbsliderdiv").imageSlider({ //initialize slider
        'thumbs': @Html.Raw(JsonConvert.SerializeObject(strAllImagesAsArray)),
        'auto_scroll':true,
        'auto_scroll_speed':4500,
        'stop_after': 2, //stop after x cycles? Set to 0 to disable.
        'canvas_width':700,
        'canvas_height':500 // <-- No comma after last option
        })
});

</script>