コード例 #1
0
        private static object BindChoice(ModelBindingContext bindingContext)
        {
            Type choiceType = bindingContext.ModelType.GetGenericArguments().FirstOrDefault();

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

            string valueKey = string.Format("{0}.Id", bindingContext.ModelName);
            var    provider = bindingContext.ValueProvider.GetValue(valueKey);

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

            var choice = bindingContext.Model ??
                         Activator.CreateInstance(typeof(Choice <>).MakeGenericType(choiceType));

            if (!string.IsNullOrEmpty(attemptedValue))
            {
                int  id      = default(int);
                bool success = false;

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

                if (success)
                {
                    var viewModel = Activator.CreateInstance(choiceType) as IEntityViewModel;
                    if (viewModel != null)
                    {
                        viewModel.Id = id;
                    }

                    GenericHelpers.SetChoiceSelection(choiceType, choice, viewModel);
                }
            }

            return(choice);
        }