3

I am developing a captcha control which allows for refresh of the captcha image. I do not have the option of storing the image on the server. I am using ASP.Net MVC for this purpose.

My controller action code:

public FileResult GetCaptchaImage()
{

    // Create a CAPTCHA image using the text stored in the Session object.
    CaptchaImage ci = new CaptchaImage(this.Session
        ["CaptchaImageText"].ToString(), 300, 75);
    // Change the response headers to output a JPEG image.
    MemoryStream stream = new MemoryStream();
    ci.Image.Save(stream, ImageFormat.Png);
    stream.Seek(0, SeekOrigin.Begin);
    return new FileStreamResult(stream, "image/png");
}

The html code to display the image in the razor view

<img id="captchaImage" class="img-responsive" src="@Url.Action("GetCaptchaImage","Home")" />

Now, when I click on the refresh button, this img should get updated. On click of the button, I am calling the same controller action again using an ajax call and it is returning the FileStreamResult.

function RefreshCaptcha() {
$.ajax({
    url: "/Home/GetCaptchaImage"
}).then(function (data) {
    console.log(data);
});

}

Now, using JQuery, how do I set the response content in the image?

Please guide. Thanks very much.

1 Answer 1

3

No need to use ajax, simply call the same URL, but pass in a no-cache querystring so it doesn't cache the value and then change the source of the image:

$('#captchaImage').attr('src', '/Home/GetCaptchaImage?nc=' + (new Date).getTime(););

In my example, I'm using epoch time, but you could simply use a random value.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much Andres. That helped.

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.