简体   繁体   中英

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

        });
    });

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

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

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.

控制器代码

查看代码

用户界面

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM