2009-10-02 5 views

Antwort

15

Versuchen Sie folgendes:

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

Formcollection ist eine Art, die wir zu ASP.NET MVC hinzugefügt, die ihre eigene Modelbinder hat. Sie können sich den Code für FormCollectionBinderAttribute ansehen, um zu sehen, was ich meine.

0

Verwenden Sie bindingContext.ValueProvider (und bindingContext.ValueProvider.TryGetValue usw.), um Werte direkt zu erhalten.

1

Der direkte Zugriff auf die Formularsammlung scheint verpönt zu sein. Das folgende Beispiel zeigt ein MVC4-Projekt, in dem ich eine benutzerdefinierte Razor-Editor-Vorlage habe, die Datum und Uhrzeit in separaten Formularfeldern erfasst. Die benutzerdefinierte Sammelmappe ruft die Werte der einzelnen Felder ab und kombiniert sie zu einem 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); 
    } 
}