1

I want to pass a json string to a Javascript function, and JSON generated dynamically. but after pass the JSON parameter in function it double quotes encode with "e;. I am using C# MVC 4.0 here is my code :-

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
  • JSON requires double-quotes. You should use the .NET JSON library to encode your array instead of doing it yourself. Commented Jul 7, 2014 at 12:50

1 Answer 1

3

What's missing in your code to make it immediatly work is :

'thumbs': @Html.Raw(strAllImages)

But it will more clean if you use JSON.net. E.g :

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

And in you 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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.