我有一个上传图像文件并检查它们是否为 jpg 的表单:
// CarAdmin/Index.cshtml
@model MySite.Models.Car
@using (Html.BeginForm("CarImageUpload", "Car", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="text" name="imageInfo" />
<input type="submit" value="OK" />
}
<form action="CarAJAX" method="post" name="CarAdminForm">
<input name="Make" value="@Model.Name/>
<input type="submit" value="Update Car Info">
</form>
// CarController.cs
[HttpPost]
public ActionResult CarImageUpload(HttpPostedFileBase file)
{
ValidateImageFile V = new ValidateImageFile(file); // checks that the file is a jpg
List<String> Validity = V.Issues;
if (Validity.Count == 0)
{
file.SaveAs(V.FilePath);
}
else
{
Response.Write(String.Join("<br>", Validity.ToArray()); // THIS IS PROBLY WRONG
}
RedirectToAction("CarAdmin");
}
public ActionResult CarAdmin()
{
return View("CarAdmin/Index.cshtml");
}
如果 ValidateImageFile 类发现问题,我想:
- 给有问题的输入上课
- 在页面上显示一条消息
但是,我不确定如何从 Controller 操作表单,而且我的 Response.Write 没有发回任何东西(我可以看到 - 但我不确定如何访问它)。
关于如何实现这一点,我有一些想法,但它们看起来像是胶带作业,而不是最佳实践。
最佳答案
用户 Darian Dimitrov 回答了一个与您的问题非常相似的问题,他的解决方案应该能为您指明正确的方向。
Is there a way to validate incoming HttpPostedFilebase files in MVC 2?
关于您正在尝试做的事情的另一个很好的资源是:
http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/
您的 View 可能如下所示:
// CarAdmin/Index.cshtml
@model MySite.Models.CarUploadViewModel
@using (Html.BeginForm("CarImageUpload", "Car", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageUpload" />
<input type="text" name="ImageInfo" />
<input type="submit" value="OK" />
}
<form action="CarAJAX" method="post" name="CarAdminForm">
<input name="Make" value="@Model.Name/>
<input type="submit" value="Update Car Info">
</form>
您的模型可能看起来像:
public class CarUploadViewModel
{
[Required]
public string ImageInfo{ get; set; }
[DataType(DataType.Upload)]
HttpPostedFileBase ImageUpload { get; set; }
}
你的 Controller 可能看起来像:
[HttpPost]
public ActionResult CarImageUpload(CarUploadViewModel model)
{
ValidateImageFile validity = new ValidateImageFile(model.ImageUpload); // checks that the file is a jpg
List<String> issues = validity.Issues;
if (issues.Count > 0)
{
// TODO: Add more descriptive issue messages
ModelState.AddModelError("ImageUpload", "There was an issue.");
}
if(ModelState.IsValid)
{
model.ImageUpload.SaveAs(V.FilePath);
RedirectToAction("CarAdmin");
}
return View(model);
}
基本上,您要做的是为您的表单创建一个模型,检查它的有效性,如果无效,将带有验证错误的模型返回给 View 。
要向模型添加自定义错误,您可以使用:
ModelState.AddModelError("MyField", "Custom error message here");
并将其输出到 View 中,如下所示:
@Html.ValidationMessage("MyField");
关于c# - 使用 MVC 显示表单错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31344998/