如何将服务器图片路径绑定到ASPxCardView的CardViewBinaryImageColumn
解决方案
CardViewBinaryImageColumn 默认绑定的是字节数组类型的图片数据,你存储的是服务器路径字符串,可根据你的需求选择以下两种方案实现绑定:
方案1:保留原生上传编辑功能,无需修改实体类
给二进制图片列增加数据项模板,直接绑定路径作为图片地址:
- 修改前台ASPxCardView的Photo列定义:
<dx:CardViewBinaryImageColumn FieldName="Photo"> <PropertiesBinaryImage ImageHeight="175px"> <EditingSettings Enabled="true" UploadSettings-UploadValidationSettings-MaxFileSize="4194304" /> </PropertiesBinaryImage> <DataItemTemplate> <dx:ASPxBinaryImage ID="imgPhoto" runat="server" ImageHeight="175px" OnDataBinding="imgPhoto_DataBinding" /> </DataItemTemplate> </dx:CardViewBinaryImageColumn>
- 后台增加绑定事件处理逻辑:
protected void imgPhoto_DataBinding(object sender, EventArgs e) { var img = sender as ASPxBinaryImage; var container = img.NamingContainer as CardViewDataItemTemplateContainer; string photoRelativePath = DataBinder.Eval(container.DataItem, "Photo")?.ToString(); if (!string.IsNullOrEmpty(photoRelativePath)) { // 相对路径转可访问的站点路径 img.ImageUrl = VirtualPathUtility.ToAbsolute(photoRelativePath); } }
该方案无需修改现有业务逻辑,同时保留了你配置的图片上传编辑功能。
方案2:转换路径为字节数组绑定
如果你不想修改前台列定义,可在数据绑定阶段读取路径对应的图片为字节数组:
- 先给你的User实体新增一个字节数组类型的属性:
public class User { // 原有属性保持不变 public byte[] PhotoBytes { get; set; } }
- 数据绑定阶段读取图片转字节数组:
User user = DBContext.getUserByID(user_id); string photoFullPath = Server.MapPath(user.Photo); if (File.Exists(photoFullPath)) { user.PhotoBytes = File.ReadAllBytes(photoFullPath); } List<User> datasource = new List<User> { user }; CardViewProfile.DataSource = datasource; CardViewProfile.DataBind();
- 修改前台列的FieldName为新增的字节数组属性:
<dx:CardViewBinaryImageColumn FieldName="PhotoBytes">
内容的提问来源于stack exchange,提问作者AlessandroF
相关产品推荐
相关产品推荐

