simba simba - 2 months ago 11
ASP.NET (C#) Question

Unable to access codebehind variable in javascript in the aspx page

I am trying to access a string from code behind into javascript in aspx page

code behind

protected void btnSearch_Click(object sender, EventArgs e)
List<string> imageList = new List<string>();
string images="";
imageList = GetMatchingImages(@"C:\Users\Shahzad\Documents\Visual Studio 2013\Projects\ImageSearchEngine\ImageSearchEngine\Images", txtSearch.Text);

foreach (var image in imageList)
images += "\"" + image + "\",";
images ="["+ images.Substring(0, images.Length - 1)+"]";


public List<string> GetMatchingImages(string path, string keyword)
var matches = new List<string>();

var images = System.IO.Directory.GetFiles(path);

foreach (var image in images)
if (image.Contains(keyword))

return matches;

and in the aspx page

<script type="text/javascript">
var imagesList;
function getImages()
return <%=images%>;
imagesList = getImages();

but it is giving error 'images does not exist in the current context' plz help me find out where I am making the mistake


This must be issue of the scope of images variable. Try declaring it outside btnSearch_Click function.

This could possibly fix the problem as images is currently inaccesible outside of this function.

Thanks, zryw141