From 9ac6ebd2b26bc21a8c5f037d3ec84deb15c4a333 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Mon, 23 Mar 2015 10:51:13 -0700 Subject: [PATCH] Refactor `IHtmlGenerator.GenerateSelect()` and address #2240 - add `IHtmlGenerator.GetCurrentValues()` method - bring together bits of `GenerateSelect()` and `UpdateSelectListItemsWithDefaultValue()` - get rid of ugly `out` parameter - also allows ` if requested. @@ -746,18 +722,137 @@ namespace Microsoft.AspNet.Mvc.Rendering modelExplorer.Metadata, _metadataProvider, viewContext.HttpContext.RequestServices); - + var validatorProviderContext = new ModelValidatorProviderContext(modelExplorer.Metadata); validatorProvider.GetValidators(validatorProviderContext); var validators = validatorProviderContext.Validators; - return + return validators .OfType() .SelectMany(v => v.GetClientValidationRules(validationContext)); } + /// + public virtual IReadOnlyCollection GetCurrentValues( + [NotNull] ViewContext viewContext, + ModelExplorer modelExplorer, + string expression, + bool allowMultiple) + { + var fullName = GetFullHtmlFieldName(viewContext, expression); + if (string.IsNullOrEmpty(fullName)) + { + throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(expression)); + } + + var type = allowMultiple ? typeof(string[]) : typeof(string); + var rawValue = GetModelStateValue(viewContext, fullName, type); + + // If ModelState did not contain a current value, fall back to ViewData- or ModelExplorer-supplied value. + if (rawValue == null) + { + if (modelExplorer == null) + { + // Html.DropDownList() and Html.ListBox() helper case. + rawValue = viewContext.ViewData.Eval(expression); + if (rawValue is IEnumerable) + { + // This ViewData item contains the fallback selectList collection for GenerateSelect(). + // Do not try to use this collection. + rawValue = null; + } + } + else + { + //