According to comments from @AndreiV and @AntP solutions:
if the string is a valid Guid string, then it will bind automatically (nothing else is required)
if the string is not a valid Guid string, then
2.1. make a conversion to the body of the action (in my opinion, this entails duplication of code) or
2.2. Set up a custom (user-defined) model binder. Below is the code for the latter approach (model binder).
// This is an example. // Note the returning of null which is undesired. // Also it does not deal with exceptions handling. Use it only as a stub. public class ExtendedModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (!(bindingContext.ModelType == typeof(Guid))) return base.BindModel(controllerContext, bindingContext); if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName)) return null; string input = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue; if (string.IsNullOrEmpty(input)) return null; Guid g; if (Guid.TryParse(input, out g)) return g; var bytes = HttpServerUtility.UrlTokenDecode(s); var result = new Guid(bytes); return result; } }
You must register with Application_Start:
ModelBinders.Binders.Add(typeof(Guid), new RealtyGuide.WebSite.Extensions.MyModelBinder());
You can use attributes instead of registering the binder globally (see here ), but I will not use it because it entails unnecessary duplication of code in my task.
Refs: 1 , 2 , 3
source share