简体   繁体   English

在控制器内部构建模型时,如何将Byte []隐式转换为字符串

[英]How to implicitly convert Byte[] to string when building model inside the controller

I am in the process of loading all the products belonging to unique categories on an index page with the request product/index/[Category ID] . 我正在使用请求product/index/[Category ID]将所有属于唯一类别的产品加载到索引页面上。

I have a ProductViewModel class which contains implicit methods to convert types between the two and also a Product entity model class. 我有一个ProductViewModel类,其中包含隐式方法以在两者之间转换类型,还包含Product实体模型类。 The implicit method to convert a Product entity to a ProductViewModel contains the method to convert a byte to a base64 string and I use this in my controller successfully to create new categories and products. Product实体转换为ProductViewModel的隐式方法包含将字节转换为base64字符串的方法,我在控制器中成功使用此方法来创建新的类别和产品。

public class ProductViewModel
    {
        public int Id { get; set; }
        [Required, Display(Name="Product Name")]
        public string Name { get; set; }
        [Required, DataType(DataType.Upload)]
        public HttpPostedFileBase Image { get; set; }
        public string OutputImage { get; set; }
        [Required]
        public Decimal Price { get; set; }

        public static byte[] ConvertToByte(ProductViewModel model)
        {
            if (model.Image != null)
            {
                byte[] imageByte = null;
                BinaryReader rdr = new BinaryReader(model.Image.InputStream);
                imageByte = rdr.ReadBytes((int)model.Image.ContentLength);

                return imageByte;
            }

            return null;
        }

        // ViewModel => Model | Implicit type Operator
        public static implicit operator Product(ProductViewModel viewModel)
        {
            var model = new Product
            {
                Id = viewModel.Id,
                Name = viewModel.Name,
                Image = ConvertToByte(viewModel),
                Price = viewModel.Price
            };

            return model;
        }

        // Model => ViewModel | Implicit type Operator
        public static implicit operator ProductViewModel(Product model)
        {
            var viewModel = new ProductViewModel
            {
                Id = model.Id,
                Name = model.Name,
                OutputImage = string.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(model.Image)),
                Price = model.Price
            };

            return viewModel;
        }

    }

However when passing a model containing all products belonging to a unique category ID to be displayed on the products View , I am not able to implicitly convert a byte to a string. 但是,当传递包含所有属于唯一类别ID的所有产品的模型以显示在产品View ,我无法将字节隐式转换为字符串。 The method that I use as an alternative is not accepted with the error: 错误不接受我用作替代方法:

LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object)' method, and this method cannot be translated into a store expression. LINQ to Entities无法识别方法'System.String Format(System.String,System.Object)',并且该方法无法转换为商店表达式。

The Model in the Controller is the following: ControllerModel如下:

var products = (await db.Categories.Where(c => c.Id == id).Select(p => p.Products.Select(x => new 
    ProductViewModel { Id = x.Id, Name = x.Name, OutputImage = (string.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(x.Image))), Price = x.Price})).ToListAsync());
return View(products);

The Model type I give the View is the following: 我为View提供的Model类型如下:

@model List<IEnumerable<ValueVille.Models.ProductViewModel>>

you can't use string.Format() in a LINQ expression instead of that you can use it in Name setter : 您不能在LINQ表达式中使用string.Format() ,而可以在Name setter中使用它:

public class ProductViewModel {

    public string Name{
      get
      {
         return this.Name;
      }
      set{
           this.Name = value;
           this.OutputImage  = string.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(value))
      }
    }
}

and in the controller : 并在控制器中:

var products = (await db.Categories.Where(c => c.Id == id).Select(p => p.Products.Select(x => new 
                    ProductViewModel { Id = x.Id, Name = x.Name, Convert.ToBase64String(x.Image))), Price = x.Price})).ToListAsync());

I initially assumed you could still assign a byte[] to a string property, to have a byte[] value inside your setter and convert from byte to string inside the setter. 最初,我假设您仍可以将string []分配给字符串属性,以在setter中具有byte []值,并在setter中将字节转换为字符串。 If the property is a string, the value assigned to this property must be already a string. 如果属性是字符串,则分配给该属性的值必须已经是字符串。

A property assignment is NOT a conversion so it will never work as long as you try to assign directly x.Image which is a byte array to OutputImage which is a string. 属性分配不是转换,因此只要您尝试直接将字节数组x.Image分配给字符串OutputImage,它就永远不会起作用。

You could keep the Image property as a byte array and to have an ImageHelper such as http://www.itorian.com/2012/10/html-helper-for-image-htmlimage.html 您可以将Image属性保留为字节数组,并拥有一个ImageHelper,例如http://www.itorian.com/2012/10/html-helper-for-image-htmlimage.html

You would keep a byte array in your model : 您将在模型中保留一个字节数组:

Image = x.Image 图片= x图片

And so you would pass this byte array to this helper. 因此,您可以将此字节数组传递给此帮助器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM