コード例 #1
0
        private static object BindChoices(ModelBindingContext bindingContext)
        {
            // By convention we append .Id in the html inputs to emphasize that we are referring to entities by their Id.
            string valueKey = string.Format("{0}.Id", bindingContext.ModelName);
            var    provider = bindingContext.ValueProvider.GetValue(valueKey);

            string attemptedValuesString = provider != null ?
                                           provider.AttemptedValue :
                                           null;

            Type choicesType = bindingContext.ModelType.GetGenericArguments().FirstOrDefault();

            if (choicesType == null)
            {
                return(null);
            }

            var choices = bindingContext.Model ??
                          Activator.CreateInstance(typeof(Choices <>).MakeGenericType(choicesType));

            if (!string.IsNullOrEmpty(attemptedValuesString))
            {
                var viewModelsList = Activator.CreateInstance(typeof(List <>).MakeGenericType(choicesType)) as IList;

                // When the HTTP params contain more than one key-value pair with the same key, they are joined with commas
                var attemptedValues = attemptedValuesString.Split(',');

                foreach (string attemptedValue in attemptedValues)
                {
                    int  id      = default(int);
                    bool success = false;

                    try
                    {
                        id      = int.Parse(attemptedValue);
                        success = true;
                    }
                    catch (FormatException ex)
                    {
                        bindingContext.ModelState.AddModelError(valueKey, ex);
                    }

                    if (success)
                    {
                        var viewModel = Activator.CreateInstance(choicesType) as IEntityViewModel;
                        viewModel.Id = id;
                        viewModelsList.Add(viewModel);
                    }
                }

                GenericHelpers.SetChoicesSelection(choicesType, choices, viewModelsList);
            }

            return(choices);
        }