This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
/
HtmlHelper.cs
1252 lines (1112 loc) · 44 KB
/
HtmlHelper.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.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
/// <summary>
/// Default implementation of <see cref="IHtmlHelper"/>.
/// </summary>
public class HtmlHelper : IHtmlHelper, IViewContextAware
{
public static readonly string ValidationInputCssClassName = "input-validation-error";
public static readonly string ValidationInputValidCssClassName = "input-validation-valid";
public static readonly string ValidationMessageCssClassName = "field-validation-error";
public static readonly string ValidationMessageValidCssClassName = "field-validation-valid";
public static readonly string ValidationSummaryCssClassName = "validation-summary-errors";
public static readonly string ValidationSummaryValidCssClassName = "validation-summary-valid";
private readonly IHtmlGenerator _htmlGenerator;
private readonly ICompositeViewEngine _viewEngine;
private readonly HtmlEncoder _htmlEncoder;
private readonly IViewBufferScope _bufferScope;
private ViewContext _viewContext;
/// <summary>
/// Initializes a new instance of the <see cref="HtmlHelper"/> class.
/// </summary>
public HtmlHelper(
IHtmlGenerator htmlGenerator,
ICompositeViewEngine viewEngine,
IModelMetadataProvider metadataProvider,
#pragma warning disable PUB0001 // Pubternal type in public API
IViewBufferScope bufferScope,
#pragma warning restore PUB0001
HtmlEncoder htmlEncoder,
UrlEncoder urlEncoder)
{
if (htmlGenerator == null)
{
throw new ArgumentNullException(nameof(htmlGenerator));
}
if (viewEngine == null)
{
throw new ArgumentNullException(nameof(viewEngine));
}
if (metadataProvider == null)
{
throw new ArgumentNullException(nameof(metadataProvider));
}
if (bufferScope == null)
{
throw new ArgumentNullException(nameof(bufferScope));
}
if (htmlEncoder == null)
{
throw new ArgumentNullException(nameof(htmlEncoder));
}
if (urlEncoder == null)
{
throw new ArgumentNullException(nameof(urlEncoder));
}
_viewEngine = viewEngine;
_htmlGenerator = htmlGenerator;
_htmlEncoder = htmlEncoder;
_bufferScope = bufferScope;
MetadataProvider = metadataProvider;
UrlEncoder = urlEncoder;
}
/// <inheritdoc />
public Html5DateRenderingMode Html5DateRenderingMode
{
get => ViewContext.Html5DateRenderingMode;
set => ViewContext.Html5DateRenderingMode = value;
}
/// <inheritdoc />
public string IdAttributeDotReplacement => _htmlGenerator.IdAttributeDotReplacement;
/// <inheritdoc />
public ViewContext ViewContext
{
get
{
if (_viewContext == null)
{
throw new InvalidOperationException(Resources.HtmlHelper_NotContextualized);
}
return _viewContext;
}
private set => _viewContext = value;
}
/// <inheritdoc />
public dynamic ViewBag => ViewContext.ViewBag;
/// <inheritdoc />
public ViewDataDictionary ViewData => ViewContext.ViewData;
/// <inheritdoc />
public ITempDataDictionary TempData => ViewContext.TempData;
/// <inheritdoc />
public UrlEncoder UrlEncoder { get; }
/// <inheritdoc />
public IModelMetadataProvider MetadataProvider { get; }
/// <summary>
/// Creates a dictionary from an object, by adding each public instance property as a key with its associated
/// value to the dictionary. It will expose public properties from derived types as well. This is typically
/// used with objects of an anonymous type.
///
/// If the <paramref name="value"/> is already an <see cref="IDictionary{String, Object}"/> instance, then it
/// is returned as-is.
/// <example>
/// <c>new { data_name="value" }</c> will translate to the entry <c>{ "data_name", "value" }</c>
/// in the resulting dictionary.
/// </example>
/// </summary>
/// <param name="value">The <see cref="object"/> to be converted.</param>
/// <returns>The created dictionary of property names and property values.</returns>
public static IDictionary<string, object> ObjectToDictionary(object value)
{
return PropertyHelper.ObjectToDictionary(value);
}
/// <summary>
/// Creates a dictionary of HTML attributes from the input object,
/// translating underscores to dashes in each public instance property.
/// </summary>
/// <param name="htmlAttributes">Anonymous object describing HTML attributes.</param>
/// <returns>A dictionary that represents HTML attributes.</returns>
/// <remarks>
/// If the object is already an <see cref="IDictionary{String, Object}"/> instance, then a shallow copy is
/// returned.
/// <example>
/// <c>new { data_name="value" }</c> will translate to the entry <c>{ "data-name", "value" }</c>
/// in the resulting dictionary.
/// </example>
/// </remarks>
public static IDictionary<string, object> AnonymousObjectToHtmlAttributes(object htmlAttributes)
{
if (htmlAttributes is IDictionary<string, object> dictionary)
{
return new Dictionary<string, object>(dictionary, StringComparer.OrdinalIgnoreCase);
}
dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
if (htmlAttributes != null)
{
foreach (var helper in HtmlAttributePropertyHelper.GetProperties(htmlAttributes.GetType()))
{
dictionary[helper.Name] = helper.GetValue(htmlAttributes);
}
}
return dictionary;
}
public virtual void Contextualize(ViewContext viewContext)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
ViewContext = viewContext;
}
/// <inheritdoc />
public IHtmlContent ActionLink(
string linkText,
string actionName,
string controllerName,
string protocol,
string hostname,
string fragment,
object routeValues,
object htmlAttributes)
{
if (linkText == null)
{
throw new ArgumentNullException(nameof(linkText));
}
var tagBuilder = _htmlGenerator.GenerateActionLink(
ViewContext,
linkText,
actionName,
controllerName,
protocol,
hostname,
fragment,
routeValues,
htmlAttributes);
if (tagBuilder == null)
{
return HtmlString.Empty;
}
return tagBuilder;
}
/// <inheritdoc />
public IHtmlContent AntiForgeryToken()
{
var html = _htmlGenerator.GenerateAntiforgery(ViewContext);
return html ?? HtmlString.Empty;
}
/// <inheritdoc />
public MvcForm BeginForm(
string actionName,
string controllerName,
object routeValues,
FormMethod method,
bool? antiforgery,
object htmlAttributes)
{
// Push the new FormContext; MvcForm.GenerateEndForm() does the corresponding pop.
_viewContext.FormContext = new FormContext
{
CanRenderAtEndOfForm = true
};
return GenerateForm(actionName, controllerName, routeValues, method, antiforgery, htmlAttributes);
}
/// <inheritdoc />
public MvcForm BeginRouteForm(
string routeName,
object routeValues,
FormMethod method,
bool? antiforgery,
object htmlAttributes)
{
// Push the new FormContext; MvcForm.GenerateEndForm() does the corresponding pop.
_viewContext.FormContext = new FormContext
{
CanRenderAtEndOfForm = true
};
return GenerateRouteForm(routeName, routeValues, method, antiforgery, htmlAttributes);
}
/// <inheritdoc />
public void EndForm()
{
var mvcForm = CreateForm();
mvcForm.EndForm();
}
/// <inheritdoc />
public IHtmlContent CheckBox(string expression, bool? isChecked, object htmlAttributes)
{
return GenerateCheckBox(
modelExplorer: null,
expression: expression,
isChecked: isChecked,
htmlAttributes: htmlAttributes);
}
/// <inheritdoc />
public string Encode(string value)
{
return _htmlGenerator.Encode(value);
}
/// <inheritdoc />
public string Encode(object value)
{
return _htmlGenerator.Encode(value);
}
/// <inheritdoc />
public string FormatValue(object value, string format)
{
return _htmlGenerator.FormatValue(value, format);
}
/// <inheritdoc />
public string GenerateIdFromName(string fullName)
{
if (fullName == null)
{
throw new ArgumentNullException(nameof(fullName));
}
return NameAndIdProvider.CreateSanitizedId(ViewContext, fullName, IdAttributeDotReplacement);
}
/// <inheritdoc />
public IHtmlContent Display(
string expression,
string templateName,
string htmlFieldName,
object additionalViewData)
{
var metadata = ExpressionMetadataProvider.FromStringExpression(expression, ViewData, MetadataProvider);
return GenerateDisplay(
metadata,
htmlFieldName ?? ExpressionHelper.GetExpressionText(expression),
templateName,
additionalViewData);
}
/// <inheritdoc />
public string DisplayName(string expression)
{
var modelExplorer = ExpressionMetadataProvider.FromStringExpression(expression, ViewData, MetadataProvider);
return GenerateDisplayName(modelExplorer, expression);
}
/// <inheritdoc />
public string DisplayText(string expression)
{
var modelExplorer = ExpressionMetadataProvider.FromStringExpression(expression, ViewData, MetadataProvider);
return GenerateDisplayText(modelExplorer);
}
/// <inheritdoc />
public IHtmlContent DropDownList(
string expression,
IEnumerable<SelectListItem> selectList,
string optionLabel,
object htmlAttributes)
{
return GenerateDropDown(
modelExplorer: null,
expression: expression,
selectList: selectList,
optionLabel: optionLabel,
htmlAttributes: htmlAttributes);
}
/// <inheritdoc />
public IHtmlContent Editor(
string expression,
string templateName,
string htmlFieldName,
object additionalViewData)
{
var modelExplorer = ExpressionMetadataProvider.FromStringExpression(expression, ViewData, MetadataProvider);
return GenerateEditor(
modelExplorer,
htmlFieldName ?? ExpressionHelper.GetExpressionText(expression),
templateName,
additionalViewData);
}
/// <inheritdoc />
public IEnumerable<SelectListItem> GetEnumSelectList<TEnum>() where TEnum : struct
{
var type = typeof(TEnum);
var metadata = MetadataProvider.GetMetadataForType(type);
if (!metadata.IsEnum || metadata.IsFlagsEnum)
{
var message = Resources.FormatHtmlHelper_TypeNotSupported_ForGetEnumSelectList(
type.FullName,
nameof(Enum).ToLowerInvariant(),
nameof(FlagsAttribute));
throw new ArgumentException(message, nameof(TEnum));
}
return GetEnumSelectList(metadata);
}
/// <inheritdoc />
public IEnumerable<SelectListItem> GetEnumSelectList(Type enumType)
{
if (enumType == null)
{
throw new ArgumentNullException(nameof(enumType));
}
var metadata = MetadataProvider.GetMetadataForType(enumType);
if (!metadata.IsEnum || metadata.IsFlagsEnum)
{
var message = Resources.FormatHtmlHelper_TypeNotSupported_ForGetEnumSelectList(
enumType.FullName,
nameof(Enum).ToLowerInvariant(),
nameof(FlagsAttribute));
throw new ArgumentException(message, nameof(enumType));
}
return GetEnumSelectList(metadata);
}
/// <inheritdoc />
public IHtmlContent Hidden(string expression, object value, object htmlAttributes)
{
return GenerateHidden(
modelExplorer: null,
expression: expression,
value: value,
useViewData: (value == null),
htmlAttributes: htmlAttributes);
}
/// <inheritdoc />
public string Id(string expression)
{
return GenerateId(expression);
}
/// <inheritdoc />
public IHtmlContent Label(string expression, string labelText, object htmlAttributes)
{
var modelExplorer = ExpressionMetadataProvider.FromStringExpression(expression, ViewData, MetadataProvider);
return GenerateLabel(
modelExplorer,
expression,
labelText,
htmlAttributes);
}
/// <inheritdoc />
public IHtmlContent ListBox(string expression, IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
return GenerateListBox(
modelExplorer: null,
expression: expression,
selectList: selectList,
htmlAttributes: htmlAttributes);
}
/// <inheritdoc />
public string Name(string expression)
{
return GenerateName(expression);
}
/// <inheritdoc />
public async Task<IHtmlContent> PartialAsync(
string partialViewName,
object model,
ViewDataDictionary viewData)
{
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
var viewBuffer = new ViewBuffer(_bufferScope, partialViewName, ViewBuffer.PartialViewPageSize);
using (var writer = new ViewBufferTextWriter(viewBuffer, Encoding.UTF8))
{
await RenderPartialCoreAsync(partialViewName, model, viewData, writer);
return viewBuffer;
}
}
/// <inheritdoc />
public Task RenderPartialAsync(string partialViewName, object model, ViewDataDictionary viewData)
{
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
return RenderPartialCoreAsync(partialViewName, model, viewData, ViewContext.Writer);
}
protected virtual IHtmlContent GenerateDisplay(
ModelExplorer modelExplorer,
string htmlFieldName,
string templateName,
object additionalViewData)
{
var templateBuilder = new TemplateBuilder(
_viewEngine,
_bufferScope,
ViewContext,
ViewData,
modelExplorer,
htmlFieldName,
templateName,
readOnly: true,
additionalViewData: additionalViewData);
return templateBuilder.Build();
}
protected virtual async Task RenderPartialCoreAsync(
string partialViewName,
object model,
ViewDataDictionary viewData,
TextWriter writer)
{
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
var viewEngineResult = _viewEngine.GetView(
ViewContext.ExecutingFilePath,
partialViewName,
isMainPage: false);
var originalLocations = viewEngineResult.SearchedLocations;
if (!viewEngineResult.Success)
{
viewEngineResult = _viewEngine.FindView(ViewContext, partialViewName, isMainPage: false);
}
if (!viewEngineResult.Success)
{
var locations = string.Empty;
if (originalLocations.Any())
{
locations = Environment.NewLine + string.Join(Environment.NewLine, originalLocations);
}
if (viewEngineResult.SearchedLocations.Any())
{
locations +=
Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations);
}
throw new InvalidOperationException(
Resources.FormatViewEngine_PartialViewNotFound(partialViewName, locations));
}
var view = viewEngineResult.View;
using (view as IDisposable)
{
// Determine which ViewData we should use to construct a new ViewData
var baseViewData = viewData ?? ViewData;
var newViewData = new ViewDataDictionary<object>(baseViewData, model);
var viewContext = new ViewContext(ViewContext, view, newViewData, writer);
await viewEngineResult.View.RenderAsync(viewContext);
}
}
/// <inheritdoc />
public IHtmlContent Password(string expression, object value, object htmlAttributes)
{
return GeneratePassword(
modelExplorer: null,
expression: expression,
value: value,
htmlAttributes: htmlAttributes);
}
/// <inheritdoc />
public IHtmlContent RadioButton(string expression, object value, bool? isChecked, object htmlAttributes)
{
return GenerateRadioButton(
modelExplorer: null,
expression: expression,
value: value,
isChecked: isChecked,
htmlAttributes: htmlAttributes);
}
/// <inheritdoc />
public IHtmlContent Raw(string value)
{
return new HtmlString(value);
}
/// <inheritdoc />
public IHtmlContent Raw(object value)
{
return new HtmlString(value?.ToString());
}
/// <inheritdoc />
public IHtmlContent RouteLink(
string linkText,
string routeName,
string protocol,
string hostName,
string fragment,
object routeValues,
object htmlAttributes)
{
if (linkText == null)
{
throw new ArgumentNullException(nameof(linkText));
}
var tagBuilder = _htmlGenerator.GenerateRouteLink(
ViewContext,
linkText,
routeName,
protocol,
hostName,
fragment,
routeValues,
htmlAttributes);
if (tagBuilder == null)
{
return HtmlString.Empty;
}
return tagBuilder;
}
/// <inheritdoc />
public IHtmlContent ValidationMessage(string expression, string message, object htmlAttributes, string tag)
{
return GenerateValidationMessage(
modelExplorer: null,
expression: expression,
message: message,
tag: tag,
htmlAttributes: htmlAttributes);
}
/// <inheritdoc />
public IHtmlContent ValidationSummary(
bool excludePropertyErrors,
string message,
object htmlAttributes,
string tag)
{
return GenerateValidationSummary(excludePropertyErrors, message, htmlAttributes, tag);
}
/// <summary>
/// Returns the HTTP method that handles form input (GET or POST) as a string.
/// </summary>
/// <param name="method">The HTTP method that handles the form.</param>
/// <returns>The form method string, either "get" or "post".</returns>
public static string GetFormMethodString(FormMethod method)
{
switch (method)
{
case FormMethod.Get:
return "get";
case FormMethod.Post:
return "post";
default:
return "post";
}
}
/// <inheritdoc />
public IHtmlContent TextArea(string expression, string value, int rows, int columns, object htmlAttributes)
{
var modelExplorer = ExpressionMetadataProvider.FromStringExpression(expression, ViewData, MetadataProvider);
if (value != null)
{
// As a special case we allow treating a string value as a model of arbitrary type.
// So pass through the string representation, even though the ModelMetadata might
// be for some other type.
//
// We do this because thought we're displaying something as a string, we want to have
// the right set of validation attributes.
modelExplorer = new ModelExplorer(
MetadataProvider,
modelExplorer.Container,
modelExplorer.Metadata,
value);
}
return GenerateTextArea(modelExplorer, expression, rows, columns, htmlAttributes);
}
/// <inheritdoc />
public IHtmlContent TextBox(string expression, object value, string format, object htmlAttributes)
{
return GenerateTextBox(
modelExplorer: null,
expression: expression,
value: value,
format: format,
htmlAttributes: htmlAttributes);
}
/// <inheritdoc />
public string Value(string expression, string format)
{
return GenerateValue(expression, value: null, format: format, useViewData: true);
}
/// <summary>
/// Override this method to return an <see cref="MvcForm"/> subclass. That subclass may change
/// <see cref="EndForm()"/> behavior.
/// </summary>
/// <returns>A new <see cref="MvcForm"/> instance.</returns>
protected virtual MvcForm CreateForm()
{
return new MvcForm(ViewContext, _htmlEncoder);
}
protected virtual IHtmlContent GenerateCheckBox(
ModelExplorer modelExplorer,
string expression,
bool? isChecked,
object htmlAttributes)
{
var checkbox = _htmlGenerator.GenerateCheckBox(
ViewContext,
modelExplorer,
expression,
isChecked,
htmlAttributes);
var hiddenForCheckbox = _htmlGenerator.GenerateHiddenForCheckbox(ViewContext, modelExplorer, expression);
if (checkbox == null || hiddenForCheckbox == null)
{
return HtmlString.Empty;
}
if (!hiddenForCheckbox.Attributes.ContainsKey("name") &&
checkbox.Attributes.TryGetValue("name", out var name))
{
// The checkbox and hidden elements should have the same name attribute value. Attributes will match
// if both are present because both have a generated value. Reach here in the special case where user
// provided a non-empty fallback name.
hiddenForCheckbox.MergeAttribute("name", name);
}
if (ViewContext.FormContext.CanRenderAtEndOfForm)
{
ViewContext.FormContext.EndOfFormContent.Add(hiddenForCheckbox);
return checkbox;
}
return new HtmlContentBuilder(capacity: 2)
.AppendHtml(checkbox)
.AppendHtml(hiddenForCheckbox);
}
protected virtual string GenerateDisplayName(ModelExplorer modelExplorer, string expression)
{
if (modelExplorer == null)
{
throw new ArgumentNullException(nameof(modelExplorer));
}
// We don't call ModelMetadata.GetDisplayName here because
// we want to fall back to the field name rather than the ModelType.
// This is similar to how the GenerateLabel get the text of a label.
var resolvedDisplayName = modelExplorer.Metadata.DisplayName ?? modelExplorer.Metadata.PropertyName;
if (resolvedDisplayName == null && expression != null)
{
var index = expression.LastIndexOf('.');
if (index == -1)
{
// Expression does not contain a dot separator.
resolvedDisplayName = expression;
}
else
{
resolvedDisplayName = expression.Substring(index + 1);
}
}
return resolvedDisplayName ?? string.Empty;
}
protected virtual string GenerateDisplayText(ModelExplorer modelExplorer)
{
return modelExplorer.GetSimpleDisplayText() ?? string.Empty;
}
protected IHtmlContent GenerateDropDown(
ModelExplorer modelExplorer,
string expression,
IEnumerable<SelectListItem> selectList,
string optionLabel,
object htmlAttributes)
{
var tagBuilder = _htmlGenerator.GenerateSelect(
ViewContext,
modelExplorer,
optionLabel,
expression,
selectList,
allowMultiple: false,
htmlAttributes: htmlAttributes);
if (tagBuilder == null)
{
return HtmlString.Empty;
}
return tagBuilder;
}
protected virtual IHtmlContent GenerateEditor(
ModelExplorer modelExplorer,
string htmlFieldName,
string templateName,
object additionalViewData)
{
var templateBuilder = new TemplateBuilder(
_viewEngine,
_bufferScope,
ViewContext,
ViewData,
modelExplorer,
htmlFieldName,
templateName,
readOnly: false,
additionalViewData: additionalViewData);
return templateBuilder.Build();
}
/// <summary>
/// Renders a <form> start tag to the response. When the user submits the form, the action with name
/// <paramref name="actionName"/> will process the request.
/// </summary>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">
/// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through
/// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically
/// created using <see cref="object"/> initializer syntax. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the route parameters.
/// </param>
/// <param name="method">The HTTP method for processing the form, either GET or POST.</param>
/// <param name="antiforgery">
/// If <c>true</c>, <form> elements will include an antiforgery token.
/// If <c>false</c>, suppresses the generation an <input> of type "hidden" with an antiforgery token.
/// If <c>null</c>, <form> elements will include an antiforgery token only if
/// <paramref name="method"/> is not <see cref="FormMethod.Get"/>.
/// </param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <returns>
/// An <see cref="MvcForm"/> instance which renders the </form> end tag when disposed.
/// </returns>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
protected virtual MvcForm GenerateForm(
string actionName,
string controllerName,
object routeValues,
FormMethod method,
bool? antiforgery,
object htmlAttributes)
{
var tagBuilder = _htmlGenerator.GenerateForm(
ViewContext,
actionName,
controllerName,
routeValues,
GetFormMethodString(method),
htmlAttributes);
if (tagBuilder != null)
{
tagBuilder.TagRenderMode = TagRenderMode.StartTag;
tagBuilder.WriteTo(ViewContext.Writer, _htmlEncoder);
}
var shouldGenerateAntiforgery = antiforgery ?? method != FormMethod.Get;
if (shouldGenerateAntiforgery)
{
ViewContext.FormContext.EndOfFormContent.Add(_htmlGenerator.GenerateAntiforgery(ViewContext));
}
return CreateForm();
}
/// <summary>
/// Renders a <form> start tag to the response. The route with name <paramref name="routeName"/>
/// generates the <form>'s <c>action</c> attribute value.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="routeValues">
/// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through
/// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically
/// created using <see cref="object"/> initializer syntax. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the route parameters.
/// </param>
/// <param name="method">The HTTP method for processing the form, either GET or POST.</param>
/// <param name="antiforgery">
/// If <c>true</c>, <form> elements will include an antiforgery token.
/// If <c>false</c>, suppresses the generation an <input> of type "hidden" with an antiforgery token.
/// If <c>null</c>, <form> elements will include an antiforgery token only if
/// <paramref name="method"/> is not <see cref="FormMethod.Get"/>.
/// </param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <returns>
/// An <see cref="MvcForm"/> instance which renders the </form> end tag when disposed.
/// </returns>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
protected virtual MvcForm GenerateRouteForm(
string routeName,
object routeValues,
FormMethod method,
bool? antiforgery,
object htmlAttributes)
{
var tagBuilder = _htmlGenerator.GenerateRouteForm(
ViewContext,
routeName,
routeValues,
GetFormMethodString(method),
htmlAttributes);
if (tagBuilder != null)
{
tagBuilder.TagRenderMode = TagRenderMode.StartTag;
tagBuilder.WriteTo(ViewContext.Writer, _htmlEncoder);
}
var shouldGenerateAntiforgery = antiforgery ?? method != FormMethod.Get;
if (shouldGenerateAntiforgery)
{
ViewContext.FormContext.EndOfFormContent.Add(_htmlGenerator.GenerateAntiforgery(ViewContext));
}
return CreateForm();
}
protected virtual IHtmlContent GenerateHidden(
ModelExplorer modelExplorer,
string expression,
object value,
bool useViewData,
object htmlAttributes)
{
var tagBuilder = _htmlGenerator.GenerateHidden(
ViewContext,
modelExplorer,
expression,
value,
useViewData,
htmlAttributes);
if (tagBuilder == null)
{
return HtmlString.Empty;
}
return tagBuilder;
}
protected virtual string GenerateId(string expression)
{
var fullName = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, expression);
return GenerateIdFromName(fullName);
}
protected virtual IHtmlContent GenerateLabel(
ModelExplorer modelExplorer,
string expression,
string labelText,
object htmlAttributes)
{
if (modelExplorer == null)
{
throw new ArgumentNullException(nameof(modelExplorer));
}
var tagBuilder = _htmlGenerator.GenerateLabel(
ViewContext,
modelExplorer,
expression,
labelText,
htmlAttributes);
if (tagBuilder == null)
{
return HtmlString.Empty;
}
// Do not generate an empty <label> element unless user passed string.Empty for the label text. This is
// primarily done for back-compatibility. (Note HtmlContentBuilder ignores (no-ops) an attempt to add
// string.Empty. So tagBuilder.HasInnerHtml isn't sufficient here.)
if (!tagBuilder.HasInnerHtml && labelText == null)
{
if (tagBuilder.Attributes.Count == 0)
{