I build a custom control with very simple ascx:
<%@ Register TagPrefix="cms" Namespace="CMS.UIControls" Assembly="CMS.UIControls" %>
<cms:MediaSelector ID="mediaSelector" runat="server" ShowClearButton="true"/>
In the code behind I can then return whatever data I want. It's a bit hacky so I'm sure you can improve on this. In my case I'm returning a custom object which is stored as JSON, but includes the GUID. You can see I'm using regex to extract the GUID from the returned URL. For completeness I've pasted my ImageModel class below, but first here's how the custom control gets the value:
public override object Value
{
get
{
var val = mediaSelector.Value;
ImageModel model = null;
if (!string.IsNullOrWhiteSpace(val))
{
// If value is relative then determine whether it's from media librry or attachment
if (val.StartsWith("~/getattachment"))
{
model = new ImageModel()
{
Source = Core.Enum.ImageSourceEnum.attachment,
MediaSelectorUrl = val
};
}
else if (val.StartsWith("~"))
{
// If value contains a GUID then assume it's a media library URL
var guids = System.Text.RegularExpressions.Regex.Matches(val, @"\b[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}\b");
Guid id;
if (guids.Count > 0 && Guid.TryParse(guids[0].Value, out id))
{
model = new ImageModel()
{
Source = Core.Enum.ImageSourceEnum.media,
MediaSelectorUrl = val,
Guid = id
};
}
}
else
{
// Use raw URL
model = new ImageModel()
{
Source = Core.Enum.ImageSourceEnum.web,
MediaSelectorUrl = val
};
}
}
if (model != null)
{
return model.ToString();
}
return null;
}
set
{
ImageModel model = null;
string val = ValidationHelper.GetString(value, null);
if (ImageModel.TryParse(val, out model))
{
mediaSelector.Value = model.MediaSelectorUrl;
return;
}
mediaSelector.Value = null;
}
}
ImageModel class:
using Newtonsoft.Json;
using Core.Enum;
using System;
using System.Runtime.Serialization;
namespace Model.ViewModel
{
[Serializable]
[DataContract]
public class ImageModel
{
[DataMember(Name = "source")]
public ImageSourceEnum Source { get; set; }
[DataMember(Name = "guid")]
public Guid? Guid { get; set; }
[DataMember(Name = "url")]
public string MediaSelectorUrl { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
public static bool TryParse(string str, out ImageModel model)
{
model = null;
if (!string.IsNullOrWhiteSpace(str))
{
try
{
model = JsonConvert.DeserializeObject<ImageModel>(str);
return true;
}
catch { }
}
return false;
}
}
}