The property is of an interface type ('IFormFile') MVC Core

北战南征 提交于 2019-12-05 18:41:46

IFormFile is a type used by the ASP.NET Core framework and it does not have a sql server type equivalent.

For your domain model store it as byte[] and when you work with views, is ok for you to use the IFormFile type.

ProductModel:

public class Product
{
    public Product()
    {
        OrderDetails = new HashSet<OrderDetails>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? CategoryId { get; set; }
    public decimal? Price { get; set; }
    public int? Quantity { get; set; }
    public string ImagePath { get; set; }

    public virtual ICollection<OrderDetails> OrderDetails { get; set; }
    public virtual Category Category { get; set; }
}

ProductViewModel:

public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? CategoryId { get; set; }
    public decimal? Price { get; set; }
    public int? Quantity { get; set; }
    public IFormFile Image { get; set; }
}

Controller method:

[HttpGet]
public IActionResult Create()
{
    var categories = _repository.GetCategories().ToList();
    var categoriesModel = categories.Select(p => new
    {
        p.Id,
        p.Name
    });

    ViewBag.Categories = new SelectList(categoriesModel, "Id", "Name");

    return View();
}

[HttpPost]
public IActionResult Create(ProductViewModel model)
{
    // Save the image to desired location and retrieve the path
    // string ImagePath = ...        

    // Add to db
    _repository.Add(new Product
    {
        Id = model.Id,
        ImagePath = ImagePath,
        // and so on
    });

    return View();
}

Also specify to the form enctype="multipart/form-data" in your view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!