據@AndreiV意見和@AntP的決定是:
如果字符串是一個正確的GUID的字符串,然後它會自動綁定(沒有別的需要),
如果字符串是不是一個正確的GUID串一個應該
2.1。在動作的正文中進行轉換(在我看來,它需要代碼複製),或者
2.2。設置自定義(用戶定義的)模型聯編程序。以下是最後一種方法(模型聯編程序)的代碼。
// 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;
}
}
登記在的Application_Start是必要的:
ModelBinders.Binders.Add(typeof(Guid), new RealtyGuide.WebSite.Extensions.MyModelBinder());
人們可以使用全局屬性,而不是粘合劑的登記(見here),但我不使用它,因爲它需要不必要的重複代碼在我的任務。
參考文獻:如果期望1,2,3
您能否詳細說明您打算如何將Gucci「打招呼」? – 2014-10-31 11:42:32
您有兩種選擇:接受一個字符串作爲輸入,然後根據您的規則進行轉換,或者創建一個自定義模型聯編程序。 – 2014-10-31 11:43:10
@AntP它只是一個例子。一般問題是將Base64字符串轉換爲Guid並向後轉換。 (在我的情況下,可以通過Guid的擴展方法投射Guid-> Base64-string)。 – Hoborg 2014-10-31 12:36:36