1

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

        });
    });
9
  • Is that TempData["Img"] data contains null on debug? Consider using ViewBag or ViewData (or a viewmodel) instead (TempData holds values between 2 subsequent requests). Commented Aug 23, 2017 at 8:27
  • 1
    You not doing anything with the view you return (e.g updating the DOM) Commented Aug 23, 2017 at 8:29
  • @TetsuyaYamamoto i did check using if null but it seems like there is value pass through to view in tempdata but it's just not showing out in view. Tried both viewBag and ViewData but result is the same. Commented Aug 23, 2017 at 8:30
  • But why are you returning a view anyway. Just return a JsonResult containing that data and update the existing src attribute (in fact you will need to create the <img> element since it does not even exist initially) Commented Aug 23, 2017 at 8:31
  • 1
    return Json(_path); and success: function (data) { $(body).append($('<img/>').attr('src', data)); } Commented Aug 23, 2017 at 8:37

4 Answers 4

2

The view uses AJAX call to controller action method as this:

$('#btnFileUpload').fileupload({
    url: '@Url.Action("UploadFile")',
    // other options
    success: function (e, data) {
        console.log("Done");
    },

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

But actually you're returning an entire view instead of JSON response in HttpPost method. To set both image path and returned message with AJAX call, you need to return JsonResult with both values like this:

[HttpPost]  
public ActionResult UploadFile(HttpPostedFileBase file)  
{
    string path;
    string msg;
    try
    {
        // file processing logic

        path = _path;
        msg = "File Uploaded Successfully!!";
    }
    catch  
    {  
        msg = "File upload failed!!";
        path = string.Empty;
    }

    var result = new { Path = path, Msg = msg }; // return both image path & upload message
    return Json(result, JsonRequestBehavior.AllowGet);
}

Then, in your AJAX call success response use append & html method to replace TempData usage:

$('#btnFileUpload').fileupload({
    url: '@Url.Action("UploadFile")',
    // other options
    success: function (data) {
        if (data.Path != '') {
            $(body).append($('<img />').attr('src', data.Path));
        }
        $('#msg').html(data.Msg); // put a div with id='msg' attribute first (see HTML code below)
        console.log("Done");
    },

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

HTML code:

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

<div id="msg"></div>

Related issue:

how to return multiple variables with jsonresult asp.net mvc3

Sign up to request clarification or add additional context in comments.

Comments

0

On the server side:

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


                    return Json(_path);
                }  
                catch  
                {  
                    return Json("");  
                }  
            }

On the client side:

        success: function (data) {
if(data==="") alert("Image hasn't been uploaded successfully!");
        else 
    { 
    $('your-div').find('img').attr('src', data);
    alert("Image has been uploaded successfully!");
    }
    }};

2 Comments

The <img> tag does not exist, so .find('img') wont work - it would need to be created
@StephenMuecke so that img should be created before file uploading. Just with css attribute display: none;. Then just use .css() function to change the value to block
0

I try your TempData["Img"] in my project. It working fine. You need to only inspect your <img src="TempData["Img"]"/> and find where you are doing mistake. Plz see the below picture for help.

Controller Code

View Code

User Interface

1 Comment

Clearly you did not test it with OP's code (making an ajax call)!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.