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



TempData["Img"]data contains null on debug? Consider usingViewBagorViewData(or a viewmodel) instead (TempData holds values between 2 subsequent requests).JsonResultcontaining that data and update the existingsrcattribute (in fact you will need to create the<img>element since it does not even exist initially)return Json(_path);andsuccess: function (data) { $(body).append($('<img/>').attr('src', data)); }