-1

I want to display an image immediately after fill the textbox, don't need to click any button for get the picture.

I did this in my view:

@using (Html.BeginForm())
{
    <input value="" id="UserID" name="UserID" type="text" class="form-control" />
    <img id="CaptchaImg" alt="Captcha" src="@Url.Action("showFoto", "loan")" style="" />
}
<script language="javascript" type="text/javascript">
    $.ajax({
        type: "POST",
        url: '@Url.Action("showFoto", "loan")',
        datatype: "image/jpg",
        success: function (UserID) {
            $('#CaptchaImg').attr('src', UserID);
        }
    });
</script>

In my controller Loan.cs:

[HttpPost]
public string showFoto(string UserID)
{
   string ImageID = UserID;
   var virtualPath = string.Format("~/images/profile/{0}.jpg", ImageID);
   if (System.IO.File.Exists(Server.MapPath(virtualPath)))
   {
      return virtualPath;
   }
   return null;
}

My information was from:get a image through jquery ajax Please, need your helps... thanks!

Community
  • 1
  • 1
Reese
  • 3
  • 3
  • Does your controller method have `[HttpPost]` attribute? – ekad Dec 04 '14 at 02:35
  • Why are you doing a POST. It should be a GET. –  Dec 04 '14 at 02:37
  • And whats the point of `ViewBag.Foto = VirtualPathUtility.ToAbsolute(virtualPath)`? –  Dec 04 '14 at 02:38
  • And the ajax call only runs when you first load the page (at which point the textbox has no value) - you need to handle the `.change()` event of the textbox and assign its value in the ajax call (your not passing any value to `showFoto()` –  Dec 04 '14 at 02:39

1 Answers1

0

Change your script to handle the .change event of the textbox and pass its value to the sever method (note the change event occurs when the textbox loses focus)

$('#UserID').change(function() {
  $.ajax({
    type: "GET",
    url: '@Url.Action("showFoto", "loan")',
    data: { userID: $(this).val() }, // pass the value of the textbox to the method
    datatype: "image/jpg",
    success: function (UserID) {
        $('#CaptchaImg').attr('src', UserID);
    }
  });
});