c# – 使用MVC显示表单错误

我有一个上传图像文件并检查它们是jpgs的表单:

// 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/

您的视图可能如下所示:

// 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; }
}

您的控制器可能如下所示:

[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);
}

基本上,您要做的是为表单创建一个Model,检查它的有效性,如果它无效,则将带有验证错误的模型返回给视图.

要向模型添加自定义错误,请使用:

ModelState.AddModelError("MyField", "Custom error message here");

并将其输出到视图,如:

@Html.ValidationMessage("MyField");
点赞