Asp.net-Mvc
為自定義模型綁定器獲取 FormCollection out controllerContext
我有一個很好的函式來獲取我的 FormCollection(由控制器提供)。現在我想做一個模型綁定,並讓我的模型綁定器呼叫該函式,它需要 FormCollection。由於某種原因,我可以找到它。我以為會是
controllerContext.HttpContext.Request.Form
嘗試這個:
var formCollection = new FormCollection(controllerContext.HttpContext.Request.Form)FormCollection 是我們添加到 ASP.NET MVC 中的一種類型,它有自己的 ModelBinder。您可以查看 FormCollectionBinderAttribute 的程式碼以了解我的意思。
直接訪問表單集合似乎不受歡迎。以下是來自 MVC4 項目的範例,其中我有一個自定義 Razor EditorTemplate,它在單獨的表單欄位中擷取日期和時間。自定義綁定器檢索各個欄位的值並將它們組合成一個
DateTime.public class DateTimeModelBinder : DefaultModelBinder { private static readonly string DATE = "Date"; private static readonly string TIME = "Time"; private static readonly string DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm"; public DateTimeModelBinder() { } public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException("bindingContext"); var provider = new FormValueProvider(controllerContext); var keys = provider.GetKeysFromPrefix(bindingContext.ModelName); if (keys.Count == 2 && keys.ContainsKey(DATE) && keys.ContainsKey(TIME)) { var date = provider.GetValue(string.Format("{0}.{1}", bindingContext.ModelName, DATE)).AttemptedValue; var time = provider.GetValue(string.Format("{0}.{1}", bindingContext.ModelName, TIME)).AttemptedValue; if (!string.IsNullOrWhiteSpace(date) && !string.IsNullOrWhiteSpace(time)) { DateTime dt; if (DateTime.TryParseExact(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} {1}", date, time), DATE_TIME_FORMAT, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AssumeLocal, out dt)) return dt; } } return base.BindModel(controllerContext, bindingContext); } }