Get FormCollection out controllerContext for Custom Model Binder

后端 未结 3 1920
醉梦人生
醉梦人生 2021-01-05 02:10

I had a nice function that took my FormCollection (provided from the controller). Now I want to do a model bind instead and have my model binder call that function and it n

相关标签:
3条回答
  • 2021-01-05 02:34

    Use bindingContext.ValueProvider (and bindingContext.ValueProvider.TryGetValue, etc.) to get values directly.

    0 讨论(0)
  • 2021-01-05 02:40

    Try this:

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

    FormCollection is a type we added to ASP.NET MVC that has its own ModelBinder. You can look at the code for FormCollectionBinderAttribute to see what I mean.

    0 讨论(0)
  • 2021-01-05 02:41

    Accessing the form collection directly appears to be frowned on. The following is an example from an MVC4 project where I have a custom Razor EditorTemplate that captures the date and time in separate form fields. The custom binder retrieves the values of the individual fields and combines them into a 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题