2009-10-02 33 views

回答

15

試試這個:

var formCollection = new FormCollection(controllerContext.HttpContext.Request.Form) 

的FormCollection是我們加入到ASP.NET MVC一個類型都有自己的ModelBinder的。您可以查看FormCollectionBinderAttribute的代碼來查看我的意思。

0

使用bindingContext.ValueProvider(和bindingContext.ValueProvider.TryGetValue等)直接獲取值。

1

直接訪問表單集合似乎被壓在了上面。以下是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); 
    } 
}