我是剃须刀视图引擎的新手。我遇到了想要上载图像浏览器的Image with Change事件的情况。一旦上传完成,如何获取json结果?
$("#billUpload").change(function(){
$('#uploadImageForm').submit();
}
Razor视图代码如下:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "uploadImageForm" }))
{
<span class="file-input btn btn-sm btn-default btn-file">
Browse…
<input id="billUpload" name="File" type="file">
</span>
}
控制器的代码是在这里:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 4; //Size = 4 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
if (!AllowedFileExtensions.Contains
(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (file.ContentLength > MaxContentLength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images/Bill/"), fileName);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message = "File uploaded successfully. File path : ~/Content/image/Bill/" + fileName;
}
}
}
return Json("Done",JsonRequestBehavior.AllowGet);
}
现在,这整个代码与上传没有问题,运行 jQuery的功能如下图像,但我不明白如何显示此警报框中的控制器返回此json消息。提前致谢。
你应该用'ajax'提交表单来做到这一点。 – Azim
在这种情况下,控制器将HttpPostedFileBase置空。我已经尝试过了。 –
你指的是什么提示框?你做一个正常的提交,所以它只是要重定向到一个新的页面(并显示“完成”,因为你返回一个'JsonResult') –