我正在根据请求将所有属于唯一类别的产品加载到索引页面上product/index/[Category ID]
。
我有一个ProductViewModel
包含隐式方法以在两者之间转换类型的类,还有一个Product实体模型类。将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;
}
}
但是,当传递包含要显示在产品上的属于唯一类别ID的所有产品的模型时View
,我无法将字节隐式转换为字符串。错误不接受我用作替代方法:
LINQ to Entities无法识别方法'System.String Format(System.String,System.Object)',并且该方法无法转换为商店表达式。
该Model
在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, OutputImage = (string.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(x.Image))), Price = x.Price})).ToListAsync());
return View(products);
在Model
我给的类型View
如下:
@model List<IEnumerable<ValueVille.Models.ProductViewModel>>
最初,我假设您仍可以将string []分配给字符串属性,以在setter中具有byte []值,并在setter中将字节转换为字符串。如果属性是字符串,则分配给该属性的值必须已经是字符串。
属性分配不是转换,因此只要您尝试直接将字节数组x.Image分配给字符串的OutputImage,它就永远不会起作用。
您可以将Image属性保留为字节数组,并拥有一个ImageHelper,例如http://www.itorian.com/2012/10/html-helper-for-image-htmlimage.html
您将在模型中保留一个字节数组:
图片= x图片
因此,您可以将此字节数组传递给此帮助器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句