此刻我正在上传任何文件并保存它。我想要的是在用户没有选择任何文件并按下上传按钮时生成一条错误消息,但此时它唯一要做的就是重定向到另一个 View ,无论它是否选择了文件。我想知道是否有另一种更好的方法来生成这些文件的上传
这是我的 Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public void Upload(HttpPostedFileBase file)
{
string file = (file.FileName).ToLower();
try
{
file.SaveAs(Server.MapPath("~/Uploads/" + file));
}
catch (Exception e)
{
ViewBag.UploadError = "Upload file error";
}
}
}
这是 View :
@{
ViewBag.Title = "Home";
}
@using (Html.BeginForm("Transformation", "Xml", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="col-md-12 offset-md-5">
<div class="custom-file col col-lg-2">
<input type="file" name="file" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
<div class="col-5">
<button class="btn btn-success col-md-4 mt-2" type="submit">Upload file</button>
</div>
</div>
//Message Error
<div class="alert alert-danger" role="alert">
<p class="text-danger">
@ViewBag.UploadError
</p>
</div>
}
最佳答案
@Thomas Caycedo Martinez,我相信您可以像下面这样简单地修改您的 Controller 方法。 如果出错,则返回到带有错误消息的同一 View 。 你的观点保持不变。
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null)
{
string fileName = (file.FileName).ToLower();
try
{
file.SaveAs(Server.MapPath("~/Uploads/" + fileName));
}
catch (Exception e)
{
ViewBag.UploadError = "Upload file error";
return View("Index");
}
}
else {
ViewBag.UploadError = "Upload file error";
return View("Index");
}
return View();
}
关于c# - 上传文件时生成错误消息 ASP.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57130064/