【问题标题】:Image upload with validation on EF Code First models在 EF Code First 模型中上传带有验证的图像
【发布时间】:2013-08-04 21:35:39
【问题描述】:

我本可以发誓这个问题应该已经被回答了一百万次,但我搜索了很长时间后还是一无所获。

我有一个绑定到对象的视图。这个对象应该以某种方式附加一个图像(我没有任何首选方法)。我想验证图像文件。我已经看到了使用属性执行此操作的方法,例如:

public class ValidateFileAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;
        if (file == null)
        {
            return false;
        }

        if (file.ContentLength > 1 * 1024 * 1024)
        {
            return false;
        }

        try
        {
            using (var img = Image.FromStream(file.InputStream))
            {
                return img.RawFormat.Equals(ImageFormat.Png);
            }
        }
        catch { }
        return false;
    }
}

但是,这需要模型中属性的 HttpPostedFileBase 类型:

public class MyViewModel
{
    [ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
    public HttpPostedFileBase File { get; set; }
}

这一切都很好,但我不能在 EF Code First 模型类中真正使用这种类型,因为它不太适合数据库存储。

那么最好的方法是什么?

【问题讨论】:

  • 是的,这就是拥有 My ViewModel 的全部意义所在。您在视图中使用 ViewModel。然后为实体创建单独的类型,然后手动或使用 Automapper 之类的东西在它们之间进行映射。
  • 我以前没听说过(我才刚接触 MVC 开发几天)。我实际上想到了另一种对我有用的解决方案。我把它贴在下面
  • 但是为所有模型设置 ViewModel 不是很多额外的工作吗?这不是有点违背 DRY 做事方式的目的吗?

标签: c# asp.net-mvc entity-framework asp.net-mvc-validation asp.net-mvc-5


【解决方案1】:

原来这是一个非常简单的解决方案。

public class MyViewModel
{
    [NotMapped, ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
    public HttpPostedFileBase File { get; set; }
}

我设置了 NotMapped 属性标签以防止它被保存在数据库中。然后在我的控制器中,我在我的对象模型中获得了 HttpPostedFileBase:

    public ActionResult Create(Product product)
    {
        if (!ModelState.IsValid)
        {
            return View(product);
        }
        // Save the file on filesystem and set the filepath in the object to be saved in the DB.
    }

【讨论】:

    【解决方案2】:

    当我进一步开发网站时,我不可避免地开始使用 ViewModels。为每个视图创建一个模型绝对是要走的路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多