每当我尝试将文件上传到服务器时,当前视图都会重定向到与控制器不同的视图。如何上传文件并保持在同一个视图中。
我尝试过以下代码:
public Action Result(HttpPostedFileBase file)
{
return new EmptyResult();
}
答案 0 :(得分:1)
Return View();
应该按照您的预期工作,返回名为结果的视图。
如果当前操作方法不是您要返回的视图,则可以使用:
return RedirectToAction("actionmethodname");
答案 1 :(得分:0)
我建议使用像plupload这样的内容进行异步上传。这样,您可以在不重定向的情况下上传,甚至在上传完成后查看图像/文档。
它允许通过不同方法进行多次上传和回退,以成功上传文件。
为了实现,您只需创建另一个控制器来处理上传。
答案 2 :(得分:0)
检查我的代码以获取MVC架构中的文章提交。
public ActionResult Submit(ArticleViewModel newSubmit, HttpPostedFileBase uploadFile)
{
if (ModelState.IsValid)
{
//Upload File
if (uploadFile != null)
{
string fileName = uploadFile.FileName;
newSubmit.Article.image = fileName;
uploadFile.SaveAs("~/Content/Uploads/Images");
string savedFileName = Path.Combine(Server.MapPath("~/Content/Uploads/Images"), uploadFile.FileName);
}
// The HTML comes encoded so we decode it before insert into database
newSubmit.Article.content = HttpUtility.HtmlDecode(newSubmit.Article.content);
//Set article flags
newSubmit.Article.flagged = true;
newSubmit.Article.finished = false;
newSubmit.Article.submitStoryFlag = true;
//Insert article in the database _repository.AddArticle(newSubmit);
return View("Submitted");
}
else
{
// Invalid – redisplay with errors
return View(newSubmit);
}
}
答案 3 :(得分:0)
假设您的视图名称是UploadView.cshtml,那么您正在上传文件。
UploadView.cshtml
@using (Html.BeginForm("UploadFile", "MyController", FormMethod.Post, new { enctype = "multipart/form-data", id = "frm", name = "frm" }))
{
<input id="FileAttachments" type="file" name="FileAttachments" />
<input type="submit" value="upload" />
}
您的控制器将是 MyController.cs
[HttpGet]
public ActionResult UploadView()
{
Return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase FileAttachments)
{
if (FileAttachments != null)
{
string fileName = System.Guid.NewGuid().ToString() + Path.GetFileName(FileAttachments.FileName);
fileName = Path.Combine(Server.MapPath("~/Content/Files"), fileName);
FileAttachments.SaveAs(fileName);
}
return View("UploadView");
}