2009-10-02 68 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); 
    } 
}