Tempdata在视图中没有显示在图像src中ASP.NET C#

时间:2017-08-23 08:24:33

标签: javascript c# asp.net asp.net-mvc

我正在尝试在控制器中设置图像URL,并在成功将img上传到文件夹后使用tempdata将其传递到查看页面。但是,即使在响应有效内容中显示了tempdata值,它也不会出现在视图中。

请让我知道我可以改进什么!谢谢!

控制器

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

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

        });
    });

4 个答案:

答案 0 :(得分:2)

视图使用AJAX调用控制器操作方法,如下所示:

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

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

但实际上您在HttpPost方法中返回整个视图而不是JSON响应。要使用AJAX调用设置图像路径和返回的消息,您需要返回JsonResult这两个值,如下所示:

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

然后,在您的AJAX通话success响应中使用append&amp; html替换TempData用法的$('#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"); } }); 方法:

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

HTML code:

public class FragmentSettings
extends PreferenceFragmentCompat
implements SharedPreferences.OnSharedPreferenceChangeListener


@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {

    addPreferencesFromResource(R.xml.app_preferences);

    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}


@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    switch(key)
    {
        case "KEY1":
            // DO STUFF
            break;

        case "KEY2":
            // DO STUFF
            break;
    }
}

相关问题:

how to return multiple variables with jsonresult asp.net mvc3

答案 1 :(得分:0)

在服务器端:

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

在客户端:

        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 :(得分:0)

我在我的项目中尝试了你的TempData [“Img”]。它工作正常。您只需要检查<img src="TempData["Img"]"/>并找到错误的位置。 Plz见下图寻求帮助。

Controller Code

View Code

User Interface

答案 3 :(得分:0)

使用Stephen Muecke方法,我能够解决问题,因为我没有对您返回的视图做任何事情。

return Json(_path); 

success: function (data) { $(body).append($('<img/>').attr('src', data)); }