lel lel - 3 years ago 153
Javascript Question

Tempdata not showing in image src in view ASP.NET C#

I am trying to set the image URL in my controller and pass it to view page using tempdata after successfully uploaded the img to folder. However, the tempdata value is not appearing in the view even though it was shown in the Response payload.

Please do let me know what can I improve on! Thanks!

Controller

[HttpGet]  
        public ActionResult UploadFile()  
        {  
            return View();  
        }

String fileName = "";
[HttpPost]  
        public ActionResult UploadFile(HttpPostedFileBase file)  
        {  
            try  
            {
string _path = "";

if (file.ContentLength > 0)  
                {

string _FileName = Path.GetFileName(DateTime.Now.ToBinary() + "-" + file.FileName);
_path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);

fileName = _FileName;

file.SaveAs(_path);
}  
                
TempData["Img"] = _path;
TempData["Msg"] = "File Uploaded Successfully!!";

System.Diagnostics.Debug.WriteLine("File Uploaded Successfully!!");

return View();
            }  
            catch  
            {  
                TempData["Msg"] = "File upload failed!!";
System.Diagnostics.Debug.WriteLine("File upload failed!!");
return View();  
            }  
        }


View (cshtml)

<div>
<input type="file" name="file" id="Upload" class="zone" />
<div id="dropZ">
<i class="fa fa-camera fa-3x" aria-hidden="true"></i>
<p class="add">Add Photo</p>

</div>

</div>

@Html.Raw(@TempData["Msg"])

if (TempData["Img"] != null)
{
<img src = "@TempData["Img"]" />
}


Javascript

$(document).ready(function () {

$('#btnFileUpload').fileupload({
url: '@Url.Action("UploadFile")',
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 1200,
imageMaxHeight: 1200,
imageCrop: false,
dataSrc: "",
success: function (e, data) {
console.log("Done");
},

error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Error");
}

});
});

lel lel
Answer Source

Using Stephen Muecke method, i was able to solved the problem as i was not doing anything with the view you return.

return Json(_path); 

and

success: function (data) { $(body).append($('<img/>').attr('src', data)); } 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download