我正在尝试在我的 Controller 中设置图像 URL,并在成功将 img 上传到文件夹后使用 tempdata 将其传递给查看页面。但是,tempdata 值没有出现在 View 中,即使它显示在响应负载中。
请让我知道我可以改进什么!谢谢!
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();
}
}
查看 (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");
}
});
});
最佳答案
View 使用 AJAX 调用 Controller 操作方法,如下所示:
$('#btnFileUpload').fileupload({
url: '@Url.Action("UploadFile")',
// other options
success: function (e, data) {
console.log("Done");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Error");
}
});
但实际上您在 HttpPost
方法中返回的是整个 View 而不是 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
和 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");
}
});
HTML代码:
<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>
相关问题:
how to return multiple variables with jsonresult asp.net mvc3
关于javascript - Tempdata 未显示在 View ASP.NET C# 中的图像 src 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45834426/