lundi 21 mai 2018

Getting Server Error while fetching images from get request of ajax call

While Executing Ajax get request to fetch image from another view of mvc asp.net getting the following console error, function is not hitting the success method :

"GET http://localhost:1879/cardimages/getimage?id=12 500 (Internal Server Error)" 

Below I am adding all three code snippets of controller, ajax call and view code of dropdown , through which i am trying to fetch the image from db

    I am trying to fetch image from dropdown selection in asp.net mvc :

    Following is AJAX code :

    <script type="text/javascript">

        $(function () {

            $("#ImageId").change(function (evt)

     {

                var DropDownSelectedVal=$("#ImageId :selected").val();

                alert(DropDownSelectedVal);

                if (DropDownSelectedVal !=null)

     {
                    alert("Success");


                    $.ajax({

                        url: "@Url.Action("GetImage", "CardImages")",

                        type: "Get",

                        dataType: 'json',
                        contentType: "Image",

                        data: { id: DropDownSelectedVal },

                        success: function (data) {
                             alert("Success");

                             $("img-upload2").attr('src', data);

                        },

                        error: function (xhr) {

                            alert("Something went wrong, please try again");

                        }

                    });

                }

            });

        });

    </script>

    Following is function in controller :

       public ActionResult GetImage(int id /* drop down value */)
            {
                var cardImage = db.CardImages.Where(x=>x.CityId == id ).FirstOrDefault();
                string dir = ConfigurationManager.AppSettings["UploadFilesPath1"].ToString() + "/";
                string logoPath = GetFileFromFolder(dir, cardImage.CardFileName + cardImage.OriginalFileName);
                if (logoPath != string.Empty)
                {
                    Byte[] bytes = System.IO.File.ReadAllBytes(logoPath);
                    cardImage.LogoImage = "data:image/jpeg;charset=utf-8;base64," + Convert.ToBase64String(bytes);
                }


                //var model = db.CardImages.Find(id); // This is for example put your code to fetch record. 
                //ViewBag.img = (from s in db.CardImages where s.CityId == id select s.CardFileName + s.OriginalFileName);


                return Json(cardImage.LogoImage);

            }


    And in view this for dropdown i am using 

      @Html.DropDownList("CityId", null,  "Select City", htmlAttributes: new { @class = "form-control", @Id = "ImageId" })

I am getting browser error in alert as Something went wrong and console error as mentioned above.




Aucun commentaire:

Enregistrer un commentaire