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!


        public ActionResult UploadFile()  
            return View();  

String fileName = "";
        public ActionResult UploadFile(HttpPostedFileBase file)  
string _path = "";

if (file.ContentLength > 0)  

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

fileName = _FileName;

TempData["Img"] = _path;
TempData["Msg"] = "File Uploaded Successfully!!";

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

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

View (cshtml)

<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>




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


$(document).ready(function () {

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

error: function (XMLHttpRequest, textStatus, errorThrown) {


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); 


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