0

I am trying to access a global javascript variable in order to pass it as part of the data to my ajax function. Struggling with how to do it because imageIndex does not exist in the current context. Javascript:

<script type="text/javascript">
        var imageIndex = 0;
        $(document).ready(function () {
            var imageIndex = 0;

            getImage();

            function getImage() {
                $.ajax({
                    type: "GET",
                    url: '@Url.Action( "GetImage", "Tally" )',
                    data: { imageName: '@(ViewBag.images[imageIndex])', contractID: '@(ViewBag.contractId)' },
                    //dataType: "image/jpeg;base64",
                    success: function (data) {
                        console.log(data);
                        $('#scanImage').attr('src', 'data:image/jpeg;base64,' + data.myImage);
                        $("#imageName").val('@(ViewBag.image)');
                        imageIndex++;
                    },
                    error: function () {
                        console.log("got error");
                    }
                });
            }
        });

    </script>
5
  • why did you initialize imageindex twice? Commented Feb 16, 2017 at 18:33
  • You have two imageIndex variables in your code, and actually both of them are in scope in your $.ajax call? Commented Feb 16, 2017 at 18:42
  • What is this @(…) syntax? I suspect you're mixing up client- and serverside processing here. Commented Feb 16, 2017 at 18:44
  • @Bergi ASP.Net MVC + Razor, it's legitimate. The issue is that it doesn't like concatenation so I'm not sure how to include a variable to access the ViewBag images array by index. Commented Feb 16, 2017 at 18:45
  • When I couldn't get the imageIndex to work initially, I tried adding a second declaration inside the document.ready to see if that would fix anything. That is why I had 2. Commented Feb 17, 2017 at 14:47

2 Answers 2

4

The Issue(s)

1. Remove one of your imageIndex initializations from the top. For all intents and purposes I'd say it really doesn't matter which one in your case.

2. imageIndex is being included as part of imageName as a string, rather than the variable's value.


The Tricky Part

Razor won't let us simply concatenate the variable as we normally would by doing something like:

imageName: '@(ViewBag.images[' + imageIndex + '])' 

Because we're including a single quote within the server-side @, C# will tell you that you have an overflowing literal.


The Solution

Instead, we'll need to populate a normal javascript array from the ViewBag.images array.

   var imageArray = @Html.Raw(Json.Encode(@ViewBag.images));
// var imageArray = ["image1", "image2", "image3"];

From there, we can now use imageArray[imageIndex] to retrieve the value we're looking for.

$(document).ready(function () {
    var imageIndex = 0;

    //Convert our ViewBag.images into a JS array
    var imageArray = @Html.Raw(Json.Encode(@ViewBag.images));
    getImage();

    function getImage() {
        $.ajax({
            type: "GET",
            url: '@Url.Action( "GetImage", "Tally" )',
            data: { imageName: imageArray[imageIndex], contractID: '@(ViewBag.contractId)' },
            //dataType: "image/jpeg;base64",
            success: function (data) {
                console.log(data);
                $('#scanImage').attr('src', 'data:image/jpeg;base64,' + data.myImage);
                $("#imageName").val('@(ViewBag.image)');
                imageIndex++;
            },
            error: function () {
                console.log("got error");
            }
        });
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

I removed one. I now have '@(ViewBag.images['+imageIndex+'])' and am getting: Error 6 Too many characters in character literal
Hmm, this is most likely C# being upset that we're using a single quote. Let me take a deeper look into this, will be a bit more tricky than I originally thought.
@dmikester1 Please see my edit and let me know if this works.
Perfect! Thank you much!
0

Hmm, I think you are getting it wrong here:

imageName: '@(ViewBag.images[imageIndex])'

try: imageName: '@(ViewBag.images[' + imageIndex + '])'

also, why are you declaring variables twice?

<script type="text/javascript">
        var imageIndex = 0; //this
        $(document).ready(function () {
            var imageIndex = 0; //and this?
....

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.