This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
DefaultHtmlGenerator.cs
1561 lines (1361 loc) · 59.5 KB
/
DefaultHtmlGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public class DefaultHtmlGenerator : IHtmlGenerator
{
private const string HiddenListItem = @"<li style=""display:none""></li>";
private static readonly MethodInfo ConvertEnumFromStringMethod =
typeof(DefaultHtmlGenerator).GetTypeInfo().GetDeclaredMethod(nameof(ConvertEnumFromString));
// See: (http://www.w3.org/TR/html5/forms.html#the-input-element)
private static readonly string[] _placeholderInputTypes =
new[] { "text", "search", "url", "tel", "email", "password", "number" };
private readonly IAntiforgery _antiforgery;
private readonly IClientModelValidatorProvider _clientModelValidatorProvider;
private readonly IModelMetadataProvider _metadataProvider;
private readonly IUrlHelperFactory _urlHelperFactory;
private readonly HtmlEncoder _htmlEncoder;
private readonly ClientValidatorCache _clientValidatorCache;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultHtmlGenerator"/> class.
/// </summary>
/// <param name="antiforgery">The <see cref="IAntiforgery"/> instance which is used to generate antiforgery
/// tokens.</param>
/// <param name="optionsAccessor">The accessor for <see cref="MvcOptions"/>.</param>
/// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param>
/// <param name="urlHelperFactory">The <see cref="IUrlHelperFactory"/>.</param>
/// <param name="htmlEncoder">The <see cref="HtmlEncoder"/>.</param>
/// <param name="clientValidatorCache">The <see cref="ClientValidatorCache"/> that provides
/// a list of <see cref="IClientModelValidator"/>s.</param>
public DefaultHtmlGenerator(
IAntiforgery antiforgery,
IOptions<MvcViewOptions> optionsAccessor,
IModelMetadataProvider metadataProvider,
IUrlHelperFactory urlHelperFactory,
HtmlEncoder htmlEncoder,
ClientValidatorCache clientValidatorCache)
{
if (antiforgery == null)
{
throw new ArgumentNullException(nameof(antiforgery));
}
if (optionsAccessor == null)
{
throw new ArgumentNullException(nameof(optionsAccessor));
}
if (metadataProvider == null)
{
throw new ArgumentNullException(nameof(metadataProvider));
}
if (urlHelperFactory == null)
{
throw new ArgumentNullException(nameof(urlHelperFactory));
}
if (htmlEncoder == null)
{
throw new ArgumentNullException(nameof(htmlEncoder));
}
if (clientValidatorCache == null)
{
throw new ArgumentNullException(nameof(clientValidatorCache));
}
_antiforgery = antiforgery;
var clientValidatorProviders = optionsAccessor.Value.ClientModelValidatorProviders;
_clientModelValidatorProvider = new CompositeClientModelValidatorProvider(clientValidatorProviders);
_metadataProvider = metadataProvider;
_urlHelperFactory = urlHelperFactory;
_htmlEncoder = htmlEncoder;
_clientValidatorCache = clientValidatorCache;
// Underscores are fine characters in id's.
IdAttributeDotReplacement = optionsAccessor.Value.HtmlHelperOptions.IdAttributeDotReplacement;
}
/// <inheritdoc />
public string IdAttributeDotReplacement { get; }
/// <inheritdoc />
public string Encode(string value)
{
return !string.IsNullOrEmpty(value) ? _htmlEncoder.Encode(value) : string.Empty;
}
/// <inheritdoc />
public string Encode(object value)
{
return (value != null) ? _htmlEncoder.Encode(value.ToString()) : string.Empty;
}
/// <inheritdoc />
public string FormatValue(object value, string format)
{
return ViewDataDictionary.FormatValue(value, format);
}
/// <inheritdoc />
public virtual TagBuilder GenerateActionLink(
ViewContext viewContext,
string linkText,
string actionName,
string controllerName,
string protocol,
string hostname,
string fragment,
object routeValues,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
if (linkText == null)
{
throw new ArgumentNullException(nameof(linkText));
}
var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);
var url = urlHelper.Action(actionName, controllerName, routeValues, protocol, hostname, fragment);
return GenerateLink(linkText, url, htmlAttributes);
}
/// <inheritdoc />
public virtual IHtmlContent GenerateAntiforgery(ViewContext viewContext)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
// If we're inside a BeginForm/BeginRouteForm, the antiforgery token might have already been
// created and appended to the 'end form' content OR the form tag helper might have already generated
// an antiforgery token.
if (viewContext.FormContext.HasAntiforgeryToken)
{
return HtmlString.Empty;
}
viewContext.FormContext.HasAntiforgeryToken = true;
return _antiforgery.GetHtml(viewContext.HttpContext);
}
/// <inheritdoc />
public virtual TagBuilder GenerateCheckBox(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
bool? isChecked,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
if (modelExplorer != null)
{
// CheckBoxFor() case. That API does not support passing isChecked directly.
Debug.Assert(!isChecked.HasValue);
if (modelExplorer.Model != null)
{
bool modelChecked;
if (bool.TryParse(modelExplorer.Model.ToString(), out modelChecked))
{
isChecked = modelChecked;
}
}
}
var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);
if (isChecked.HasValue && htmlAttributeDictionary != null)
{
// Explicit isChecked value must override "checked" in dictionary.
htmlAttributeDictionary.Remove("checked");
}
// Use ViewData only in CheckBox case (metadata null) and when the user didn't pass an isChecked value.
return GenerateInput(
viewContext,
InputType.CheckBox,
modelExplorer,
expression,
value: "true",
useViewData: (modelExplorer == null && !isChecked.HasValue),
isChecked: isChecked ?? false,
setId: true,
isExplicitValue: false,
format: null,
htmlAttributes: htmlAttributeDictionary);
}
/// <inheritdoc />
public virtual TagBuilder GenerateHiddenForCheckbox(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttribute("type", GetInputTypeString(InputType.Hidden));
tagBuilder.MergeAttribute("value", "false");
tagBuilder.TagRenderMode = TagRenderMode.SelfClosing;
var fullName = GetFullHtmlFieldName(viewContext, expression);
tagBuilder.MergeAttribute("name", fullName);
return tagBuilder;
}
/// <inheritdoc />
public virtual TagBuilder GenerateForm(
ViewContext viewContext,
string actionName,
string controllerName,
object routeValues,
string method,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var defaultMethod = false;
if (string.IsNullOrEmpty(method))
{
defaultMethod = true;
}
else if (string.Equals(method, "post", StringComparison.OrdinalIgnoreCase))
{
defaultMethod = true;
}
string action;
if (actionName == null && controllerName == null && routeValues == null && defaultMethod)
{
// Submit to the original URL in the special case that user called the BeginForm() overload without
// parameters (except for the htmlAttributes parameter). Also reachable in the even-more-unusual case
// that user called another BeginForm() overload with default argument values.
var request = viewContext.HttpContext.Request;
action = request.PathBase + request.Path + request.QueryString;
}
else
{
var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);
action = urlHelper.Action(action: actionName, controller: controllerName, values: routeValues);
}
return GenerateFormCore(viewContext, action, method, htmlAttributes);
}
/// <inheritdoc />
public TagBuilder GenerateRouteForm(
ViewContext viewContext,
string routeName,
object routeValues,
string method,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);
var action = urlHelper.RouteUrl(routeName, routeValues);
return GenerateFormCore(viewContext, action, method, htmlAttributes);
}
/// <inheritdoc />
public virtual TagBuilder GenerateHidden(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
object value,
bool useViewData,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
// Special-case opaque values and arbitrary binary data.
var byteArrayValue = value as byte[];
if (byteArrayValue != null)
{
value = Convert.ToBase64String(byteArrayValue);
}
var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);
return GenerateInput(
viewContext,
InputType.Hidden,
modelExplorer,
expression,
value,
useViewData,
isChecked: false,
setId: true,
isExplicitValue: true,
format: null,
htmlAttributes: htmlAttributeDictionary);
}
/// <inheritdoc />
public virtual TagBuilder GenerateLabel(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
string labelText,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
if (modelExplorer == null)
{
throw new ArgumentNullException(nameof(modelExplorer));
}
var resolvedLabelText = labelText ??
modelExplorer.Metadata.DisplayName ??
modelExplorer.Metadata.PropertyName;
if (resolvedLabelText == null)
{
resolvedLabelText =
string.IsNullOrEmpty(expression) ? string.Empty : expression.Split('.').Last();
}
if (string.IsNullOrEmpty(resolvedLabelText))
{
return null;
}
var tagBuilder = new TagBuilder("label");
var idString =
TagBuilder.CreateSanitizedId(GetFullHtmlFieldName(viewContext, expression), IdAttributeDotReplacement);
tagBuilder.Attributes.Add("for", idString);
tagBuilder.InnerHtml.SetContent(resolvedLabelText);
tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes), replaceExisting: true);
return tagBuilder;
}
/// <inheritdoc />
public virtual TagBuilder GeneratePassword(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
object value,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);
return GenerateInput(
viewContext,
InputType.Password,
modelExplorer,
expression,
value,
useViewData: false,
isChecked: false,
setId: true,
isExplicitValue: true,
format: null,
htmlAttributes: htmlAttributeDictionary);
}
/// <inheritdoc />
public virtual TagBuilder GenerateRadioButton(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
object value,
bool? isChecked,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);
if (modelExplorer == null)
{
// RadioButton() case. Do not override checked attribute if isChecked is implicit.
if (!isChecked.HasValue &&
(htmlAttributeDictionary == null || !htmlAttributeDictionary.ContainsKey("checked")))
{
// Note value may be null if isChecked is non-null.
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
// isChecked not provided nor found in the given attributes; fall back to view data.
var valueString = Convert.ToString(value, CultureInfo.CurrentCulture);
isChecked = string.Equals(
EvalString(viewContext, expression),
valueString,
StringComparison.OrdinalIgnoreCase);
}
}
else
{
// RadioButtonFor() case. That API does not support passing isChecked directly.
Debug.Assert(!isChecked.HasValue);
// Need a value to determine isChecked.
Debug.Assert(value != null);
var model = modelExplorer.Model;
var valueString = Convert.ToString(value, CultureInfo.CurrentCulture);
isChecked = model != null &&
string.Equals(model.ToString(), valueString, StringComparison.OrdinalIgnoreCase);
}
if (isChecked.HasValue && htmlAttributeDictionary != null)
{
// Explicit isChecked value must override "checked" in dictionary.
htmlAttributeDictionary.Remove("checked");
}
return GenerateInput(
viewContext,
InputType.Radio,
modelExplorer,
expression,
value,
useViewData: false,
isChecked: isChecked ?? false,
setId: true,
isExplicitValue: true,
format: null,
htmlAttributes: htmlAttributeDictionary);
}
/// <inheritdoc />
public virtual TagBuilder GenerateRouteLink(
ViewContext viewContext,
string linkText,
string routeName,
string protocol,
string hostName,
string fragment,
object routeValues,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
if (linkText == null)
{
throw new ArgumentNullException(nameof(linkText));
}
var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);
var url = urlHelper.RouteUrl(routeName, routeValues, protocol, hostName, fragment);
return GenerateLink(linkText, url, htmlAttributes);
}
/// <inheritdoc />
public TagBuilder GenerateSelect(
ViewContext viewContext,
ModelExplorer modelExplorer,
string optionLabel,
string expression,
IEnumerable<SelectListItem> selectList,
bool allowMultiple,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var currentValues = GetCurrentValues(viewContext, modelExplorer, expression, allowMultiple);
return GenerateSelect(
viewContext,
modelExplorer,
optionLabel,
expression,
selectList,
currentValues,
allowMultiple,
htmlAttributes);
}
/// <inheritdoc />
public virtual TagBuilder GenerateSelect(
ViewContext viewContext,
ModelExplorer modelExplorer,
string optionLabel,
string expression,
IEnumerable<SelectListItem> selectList,
ICollection<string> currentValues,
bool allowMultiple,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var fullName = GetFullHtmlFieldName(viewContext, expression);
if (string.IsNullOrEmpty(fullName))
{
throw new ArgumentException(
Resources.FormatHtmlGenerator_FieldNameCannotBeNullOrEmpty(
typeof(IHtmlHelper).FullName,
nameof(IHtmlHelper.Editor),
typeof(IHtmlHelper<>).FullName,
nameof(IHtmlHelper<object>.EditorFor),
"htmlFieldName"),
nameof(expression));
}
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = GetSelectListItems(viewContext, expression);
}
modelExplorer = modelExplorer ??
ExpressionMetadataProvider.FromStringExpression(expression, viewContext.ViewData, _metadataProvider);
// Convert each ListItem to an <option> tag and wrap them with <optgroup> if requested.
var listItemBuilder = GenerateGroupsAndOptions(optionLabel, selectList, currentValues);
var tagBuilder = new TagBuilder("select");
tagBuilder.InnerHtml.SetHtmlContent(listItemBuilder);
tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));
tagBuilder.MergeAttribute("name", fullName, true /* replaceExisting */);
tagBuilder.GenerateId(fullName, IdAttributeDotReplacement);
if (allowMultiple)
{
tagBuilder.MergeAttribute("multiple", "multiple");
}
// If there are any errors for a named field, we add the css attribute.
ModelStateEntry entry;
if (viewContext.ViewData.ModelState.TryGetValue(fullName, out entry))
{
if (entry.Errors.Count > 0)
{
tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
}
}
AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression);
return tagBuilder;
}
/// <inheritdoc />
public virtual TagBuilder GenerateTextArea(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
int rows,
int columns,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
if (rows < 0)
{
throw new ArgumentOutOfRangeException(nameof(rows), Resources.HtmlHelper_TextAreaParameterOutOfRange);
}
if (columns < 0)
{
throw new ArgumentOutOfRangeException(
nameof(columns),
Resources.HtmlHelper_TextAreaParameterOutOfRange);
}
var fullName = GetFullHtmlFieldName(viewContext, expression);
if (string.IsNullOrEmpty(fullName))
{
throw new ArgumentException(
Resources.FormatHtmlGenerator_FieldNameCannotBeNullOrEmpty(
typeof(IHtmlHelper).FullName,
nameof(IHtmlHelper.Editor),
typeof(IHtmlHelper<>).FullName,
nameof(IHtmlHelper<object>.EditorFor),
"htmlFieldName"),
nameof(expression));
}
ModelStateEntry entry;
viewContext.ViewData.ModelState.TryGetValue(fullName, out entry);
var value = string.Empty;
if (entry != null && entry.AttemptedValue != null)
{
value = entry.AttemptedValue;
}
else if (modelExplorer.Model != null)
{
value = modelExplorer.Model.ToString();
}
var tagBuilder = new TagBuilder("textarea");
tagBuilder.GenerateId(fullName, IdAttributeDotReplacement);
tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes), true);
if (rows > 0)
{
tagBuilder.MergeAttribute("rows", rows.ToString(CultureInfo.InvariantCulture), true);
}
if (columns > 0)
{
tagBuilder.MergeAttribute("columns", columns.ToString(CultureInfo.InvariantCulture), true);
}
tagBuilder.MergeAttribute("name", fullName, true);
AddPlaceholderAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);
AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression);
// If there are any errors for a named field, we add this CSS attribute.
if (entry != null && entry.Errors.Count > 0)
{
tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
}
// The first newline is always trimmed when a TextArea is rendered, so we add an extra one
// in case the value being rendered is something like "\r\nHello"
tagBuilder.InnerHtml.AppendLine();
tagBuilder.InnerHtml.Append(value);
return tagBuilder;
}
/// <inheritdoc />
public virtual TagBuilder GenerateTextBox(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
object value,
string format,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);
return GenerateInput(
viewContext,
InputType.Text,
modelExplorer,
expression,
value,
useViewData: (modelExplorer == null && value == null),
isChecked: false,
setId: true,
isExplicitValue: true,
format: format,
htmlAttributes: htmlAttributeDictionary);
}
/// <inheritdoc />
public virtual TagBuilder GenerateValidationMessage(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
string message,
string tag,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var fullName = GetFullHtmlFieldName(viewContext, expression);
if (string.IsNullOrEmpty(fullName))
{
throw new ArgumentException(
Resources.FormatHtmlGenerator_FieldNameCannotBeNullOrEmpty(
typeof(IHtmlHelper).FullName,
nameof(IHtmlHelper.Editor),
typeof(IHtmlHelper<>).FullName,
nameof(IHtmlHelper<object>.EditorFor),
"htmlFieldName"),
nameof(expression));
}
var formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null;
if (!viewContext.ViewData.ModelState.ContainsKey(fullName) && formContext == null)
{
return null;
}
ModelStateEntry entry;
var tryGetModelStateResult = viewContext.ViewData.ModelState.TryGetValue(fullName, out entry);
var modelErrors = tryGetModelStateResult ? entry.Errors : null;
ModelError modelError = null;
if (modelErrors != null && modelErrors.Count != 0)
{
modelError = modelErrors.FirstOrDefault(m => !string.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0];
}
if (modelError == null && formContext == null)
{
return null;
}
// Even if there are no model errors, we generate the span and add the validation message
// if formContext is not null.
if (string.IsNullOrEmpty(tag))
{
tag = viewContext.ValidationMessageElement;
}
var tagBuilder = new TagBuilder(tag);
tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));
// Only the style of the span is changed according to the errors if message is null or empty.
// Otherwise the content and style is handled by the client-side validation.
var className = (modelError != null) ?
HtmlHelper.ValidationMessageCssClassName :
HtmlHelper.ValidationMessageValidCssClassName;
tagBuilder.AddCssClass(className);
if (!string.IsNullOrEmpty(message))
{
tagBuilder.InnerHtml.SetContent(message);
}
else if (modelError != null)
{
modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(
expression,
viewContext.ViewData,
_metadataProvider);
tagBuilder.InnerHtml.SetContent(
ValidationHelpers.GetModelErrorMessageOrDefault(modelError, entry, modelExplorer));
}
if (formContext != null)
{
tagBuilder.MergeAttribute("data-valmsg-for", fullName);
var replaceValidationMessageContents = string.IsNullOrEmpty(message);
tagBuilder.MergeAttribute("data-valmsg-replace",
replaceValidationMessageContents.ToString().ToLowerInvariant());
}
return tagBuilder;
}
/// <inheritdoc />
public virtual TagBuilder GenerateValidationSummary(
ViewContext viewContext,
bool excludePropertyErrors,
string message,
string headerTag,
object htmlAttributes)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
if (viewContext.ViewData.ModelState.IsValid && (!viewContext.ClientValidationEnabled || excludePropertyErrors))
{
// No client side validation/updates
return null;
}
var wrappedMessage = new HtmlContentBuilder();
if (!string.IsNullOrEmpty(message))
{
if (string.IsNullOrEmpty(headerTag))
{
headerTag = viewContext.ValidationSummaryMessageElement;
}
var messageTag = new TagBuilder(headerTag);
messageTag.InnerHtml.SetContent(message);
wrappedMessage.AppendLine(messageTag);
}
else
{
wrappedMessage = null;
}
// If excludePropertyErrors is true, describe any validation issue with the current model in a single item.
// Otherwise, list individual property errors.
var isHtmlSummaryModified = false;
var modelStates = ValidationHelpers.GetModelStateList(viewContext.ViewData, excludePropertyErrors);
var htmlSummary = new TagBuilder("ul");
foreach (var modelState in modelStates)
{
// Perf: Avoid allocations
for (var i = 0; i < modelState.Errors.Count; i++)
{
var modelError = modelState.Errors[i];
var errorText = ValidationHelpers.GetModelErrorMessageOrDefault(modelError);
if (!string.IsNullOrEmpty(errorText))
{
var listItem = new TagBuilder("li");
listItem.InnerHtml.SetContent(errorText);
htmlSummary.InnerHtml.AppendLine(listItem);
isHtmlSummaryModified = true;
}
}
}
if (!isHtmlSummaryModified)
{
htmlSummary.InnerHtml.AppendHtml(HiddenListItem);
htmlSummary.InnerHtml.AppendLine();
}
var tagBuilder = new TagBuilder("div");
tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));
if (viewContext.ViewData.ModelState.IsValid)
{
tagBuilder.AddCssClass(HtmlHelper.ValidationSummaryValidCssClassName);
}
else
{
tagBuilder.AddCssClass(HtmlHelper.ValidationSummaryCssClassName);
}
tagBuilder.InnerHtml.AppendHtml(wrappedMessage);
tagBuilder.InnerHtml.AppendHtml(htmlSummary);
if (viewContext.ClientValidationEnabled && !excludePropertyErrors)
{
// Inform the client where to replace the list of property errors after validation.
tagBuilder.MergeAttribute("data-valmsg-summary", "true");
}
return tagBuilder;
}
/// <inheritdoc />
public virtual ICollection<string> GetCurrentValues(
ViewContext viewContext,
ModelExplorer modelExplorer,
string expression,
bool allowMultiple)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var fullName = GetFullHtmlFieldName(viewContext, expression);
if (string.IsNullOrEmpty(fullName))
{
throw new ArgumentException(
Resources.FormatHtmlGenerator_FieldNameCannotBeNullOrEmpty(
typeof(IHtmlHelper).FullName,
nameof(IHtmlHelper.Editor),
typeof(IHtmlHelper<>).FullName,
nameof(IHtmlHelper<object>.EditorFor),
"htmlFieldName"),
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<SelectListItem>)
{
// This ViewData item contains the fallback selectList collection for GenerateSelect().
// Do not try to use this collection.
rawValue = null;
}
}
else
{
// <select/>, Html.DropDownListFor() and Html.ListBoxFor() helper case. Do not use ViewData.
rawValue = modelExplorer.Model;
}
if (rawValue == null)
{
return null;
}
}
// Convert raw value to a collection.
IEnumerable rawValues;
if (allowMultiple)
{
rawValues = rawValue as IEnumerable;
if (rawValues == null || rawValues is string)
{
throw new InvalidOperationException(
Resources.FormatHtmlHelper_SelectExpressionNotEnumerable(nameof(expression)));
}
}
else
{
rawValues = new[] { rawValue };
}
modelExplorer = modelExplorer ??
ExpressionMetadataProvider.FromStringExpression(expression, viewContext.ViewData, _metadataProvider);
var metadata = modelExplorer.Metadata;
if (allowMultiple && metadata.IsEnumerableType)
{
metadata = metadata.ElementMetadata;
}
var enumNames = metadata.EnumNamesAndValues;
var isTargetEnum = metadata.IsEnum;
// Logic below assumes isTargetEnum and enumNames are consistent. Confirm that expectation is met.
Debug.Assert(isTargetEnum ^ enumNames == null);
var innerType = metadata.UnderlyingOrModelType;
// Convert raw value collection to strings.
var currentValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var value in rawValues)
{
// Add original or converted string.
var stringValue = (value as string) ?? Convert.ToString(value, CultureInfo.CurrentCulture);
// Do not add simple names of enum properties here because whitespace isn't relevant for their binding.
// Will add matching names just below.
if (enumNames == null || !enumNames.ContainsKey(stringValue.Trim()))
{
currentValues.Add(stringValue);
}
// Remainder handles isEnum cases. Convert.ToString() returns field names for enum values but select
// list may (well, should) contain integer values.
var enumValue = value as Enum;
if (isTargetEnum && enumValue == null && value != null)
{
var valueType = value.GetType();
if (typeof(long).IsAssignableFrom(valueType) || typeof(ulong).IsAssignableFrom(valueType))
{
// E.g. user added an int to a ViewData entry and called a string-based HTML helper.
enumValue = ConvertEnumFromInteger(value, innerType);