本文整理汇总了C#中TagBuilder.ToHtmlString方法的典型用法代码示例。如果您正苦于以下问题:C# TagBuilder.ToHtmlString方法的具体用法?C# TagBuilder.ToHtmlString怎么用?C# TagBuilder.ToHtmlString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TagBuilder
的用法示例。
在下文中一共展示了TagBuilder.ToHtmlString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateNumericPager
public static HtmlString CreateNumericPager(this IHtmlHelper helper,
int totalNumResults,
int itemsPerPage,
int currentPage,
string pagerCssClassName = "pagination",
string activeCssClassName = "active")
{
if (totalNumResults <= itemsPerPage)
{
//no pager needed
return HtmlString.Empty;
}
else
{
int numberOfPages = totalNumResults / itemsPerPage;
int maxNumberOfPagesShown = 20;
bool showFirstAndLast = numberOfPages > maxNumberOfPagesShown;
int startPage = getStartPage(numberOfPages, currentPage);
int endPage = getEndPage(numberOfPages, currentPage, startPage);
StringBuilder builder = new StringBuilder();
builder.Append(string.Format(@"<ul class=""{0}"">",pagerCssClassName));
if (showFirstAndLast && startPage > 1)
{
builder.Append("<li>");
builder.Append(buildActionLink(helper, "...", 1));
builder.Append("</li>");
}
for (int i = startPage; i <= endPage; i++)
{
string PageLinkText = i.ToString();
if (i != currentPage)
{
builder.Append("<li>");
builder.Append(buildActionLink(helper, PageLinkText, i));
}
else
{
builder.Append(string.Format(@"<li class=""{0}"">", activeCssClassName));
builder.Append(string.Format(@"<a href=""#"">{0}</a>",i));
}
builder.Append(" </li>");
}
if (showFirstAndLast && (endPage != numberOfPages))
{
builder.Append("<li>");
builder.Append(buildActionLink(helper, "...", numberOfPages));
builder.Append("</li>");
}
builder.Append("</ul>");
var tagBuilder = new TagBuilder("div");
tagBuilder.InnerHtml = builder.ToString();
return tagBuilder.ToHtmlString(TagRenderMode.Normal);
}
}
示例2: BuildValidationMessage
private IHtmlString BuildValidationMessage(string name, string message, IDictionary<string, object> htmlAttributes)
{
var modelState = ModelState[name];
IEnumerable<string> errors = null;
if (modelState != null)
{
errors = modelState.Errors;
}
bool hasError = errors != null && errors.Any();
if (!hasError && !UnobtrusiveJavaScriptEnabled)
{
// If unobtrusive validation is enabled, we need to generate an empty span with the "val-for" attribute"
return null;
}
else
{
string error = null;
if (hasError)
{
error = message ?? errors.First();
}
TagBuilder tagBuilder = new TagBuilder("span") { InnerHtml = Encode(error) };
tagBuilder.MergeAttributes(htmlAttributes);
if (UnobtrusiveJavaScriptEnabled)
{
bool replaceValidationMessageContents = String.IsNullOrEmpty(message);
tagBuilder.MergeAttribute("data-valmsg-for", name);
tagBuilder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
}
tagBuilder.AddCssClass(hasError ? ValidationMessageCssClassName : ValidationMessageValidCssClassName);
return tagBuilder.ToHtmlString(TagRenderMode.Normal);
}
}
示例3: BuildCheckBox
private IHtmlString BuildCheckBox(string name, bool? isChecked, IDictionary<string, object> attributes)
{
TagBuilder builder = new TagBuilder("input");
builder.MergeAttribute("type", "checkbox", replaceExisting: true);
builder.GenerateId(name);
builder.MergeAttributes(attributes, replaceExisting: true);
builder.MergeAttribute("name", name, replaceExisting: true);
if (UnobtrusiveJavaScriptEnabled)
{
var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name);
builder.MergeAttributes(validationAttributes, replaceExisting: false);
}
var model = ModelState[name];
if (model != null && model.Value != null)
{
bool modelValue = (bool)ConvertTo(model.Value, typeof(bool));
isChecked = isChecked ?? modelValue;
}
if (isChecked.HasValue)
{
if (isChecked.Value == true)
{
builder.MergeAttribute("checked", "checked", replaceExisting: true);
}
else
{
builder.Attributes.Remove("checked");
}
}
AddErrorClass(builder, name);
return builder.ToHtmlString(TagRenderMode.SelfClosing);
}
示例4: BuildRadioButton
private IHtmlString BuildRadioButton(string name, object value, bool? isChecked, IDictionary<string, object> attributes) {
string valueString = ConvertTo(value, typeof(string)) as string;
TagBuilder builder = new TagBuilder("input");
builder.MergeAttribute("type", "radio", true);
builder.GenerateId(name);
builder.MergeAttributes(attributes, replaceExisting: true);
builder.MergeAttribute("value", valueString, replaceExisting: true);
builder.MergeAttribute("name", name, replaceExisting: true);
var modelState = ModelState[name];
string modelValue = null;
if (modelState != null) {
modelValue = ConvertTo(modelState.Value, typeof(string)) as string;
isChecked = isChecked ?? String.Equals(modelValue, valueString, StringComparison.OrdinalIgnoreCase);
}
if (isChecked.HasValue) {
// Overrides attribute values
if (isChecked.Value) {
builder.MergeAttribute("checked", "checked", true);
}
else {
builder.Attributes.Remove("checked");
}
}
AddErrorClass(builder, name);
return builder.ToHtmlString(TagRenderMode.SelfClosing);
}
示例5: GenerateAntiforgery
public override HtmlString GenerateAntiforgery(ViewContext viewContext)
{
var tagBuilder = new TagBuilder("input", new CommonTestEncoder())
{
Attributes =
{
{ "name", "__RequestVerificationToken" },
{ "type", "hidden" },
{ "value", "olJlUDjrouRNWLen4tQJhauj1Z1rrvnb3QD65cmQU1Ykqi6S4" }, // 50 chars of a token.
},
};
return tagBuilder.ToHtmlString(TagRenderMode.SelfClosing);
}
示例6: Label
public IHtmlString Label(string labelText, string labelFor, IDictionary<string, object> attributes) {
if (String.IsNullOrEmpty(labelText)) {
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "labelText");
}
labelFor = labelFor ?? labelText;
TagBuilder tag = new TagBuilder("label") { InnerHtml = Encode(labelText) };
if (!String.IsNullOrEmpty(labelFor)) {
tag.MergeAttribute("for", labelFor);
}
tag.MergeAttributes(attributes, false);
return tag.ToHtmlString(TagRenderMode.Normal);
}
示例7: BuildValidationMessage
private IHtmlString BuildValidationMessage(string name, string message, IDictionary<string, object> htmlAttributes) {
if (ModelState.IsValidField(name)) {
return null;
}
else {
IEnumerable<string> errors = ModelState[name].Errors;
var error = message ?? errors.FirstOrDefault();
if (error == null) {
return null;
}
TagBuilder tagBuilder = new TagBuilder("span") { InnerHtml = Encode(error) };
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.AddCssClass(ValidationInputCssClassName);
return tagBuilder.ToHtmlString(TagRenderMode.Normal);
}
}
示例8: Image
public static HtmlString Image(this IHtmlHelper helper, string src, string alt = null)
{
if (string.IsNullOrWhiteSpace(src))
{
throw new ArgumentOutOfRangeException(nameof(src), src, "Must not be null or whitespace");
}
var img = new TagBuilder("img");
img.MergeAttribute("src", GetCdnSource(src));
if (!string.IsNullOrWhiteSpace(alt))
{
img.MergeAttribute("alt", alt);
}
return img.ToHtmlString(TagRenderMode.SelfClosing);
}
示例9: BuildInputField
private IHtmlString BuildInputField(string name, InputType type, object value, bool isExplicitValue,
IDictionary<string, object> attributes)
{
TagBuilder tagBuilder = new TagBuilder("input");
// Implicit parameters
tagBuilder.MergeAttribute("type", GetInputTypeString(type));
tagBuilder.GenerateId(name);
// Overwrite implicit
tagBuilder.MergeAttributes(attributes, replaceExisting: true);
if (UnobtrusiveJavaScriptEnabled)
{
// Add validation attributes
var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name);
tagBuilder.MergeAttributes(validationAttributes, replaceExisting: false);
}
// Function arguments
tagBuilder.MergeAttribute("name", name, replaceExisting: true);
var modelState = ModelState[name];
if ((type != InputType.Password) && modelState != null)
{
// Don't use model values for passwords
value = value ?? modelState.Value ?? String.Empty;
}
if ((type != InputType.Password) || ((type == InputType.Password) && (value != null)))
{
// Review: Do we really need to be this pedantic about sticking to mvc?
tagBuilder.MergeAttribute("value", (string)ConvertTo(value, typeof(string)), replaceExisting: isExplicitValue);
}
AddErrorClass(tagBuilder, name);
return tagBuilder.ToHtmlString(TagRenderMode.SelfClosing);
}
示例10: GenerateValidationSummary
protected virtual HtmlString GenerateValidationSummary(
bool excludePropertyErrors,
string message,
IDictionary<string, object> htmlAttributes,
string tag)
{
var formContext = ViewContext.ClientValidationEnabled ? ViewContext.FormContext : null;
if (ViewData.ModelState.IsValid && (formContext == null || excludePropertyErrors))
{
// No client side validation/updates
return HtmlString.Empty;
}
string wrappedMessage;
if (!string.IsNullOrEmpty(message))
{
if (string.IsNullOrEmpty(tag))
{
tag = ViewContext.ValidationSummaryMessageElement;
}
var messageTag = new TagBuilder(tag);
messageTag.SetInnerText(message);
wrappedMessage = messageTag.ToString(TagRenderMode.Normal) + Environment.NewLine;
}
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 htmlSummary = new StringBuilder();
var modelStates = ValidationHelpers.GetModelStateList(ViewData, excludePropertyErrors);
foreach (var modelState in modelStates)
{
foreach (var modelError in modelState.Errors)
{
var errorText = ValidationHelpers.GetUserErrorMessageOrDefault(modelError, modelState: null);
if (!string.IsNullOrEmpty(errorText))
{
var listItem = new TagBuilder("li");
listItem.SetInnerText(errorText);
htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
}
}
}
if (htmlSummary.Length == 0)
{
htmlSummary.AppendLine(HiddenListItem);
}
var unorderedList = new TagBuilder("ul")
{
InnerHtml = htmlSummary.ToString()
};
var divBuilder = new TagBuilder("div");
divBuilder.MergeAttributes(htmlAttributes);
if (ViewData.ModelState.IsValid)
{
divBuilder.AddCssClass(HtmlHelper.ValidationSummaryValidCssClassName);
}
else
{
divBuilder.AddCssClass(HtmlHelper.ValidationSummaryCssClassName);
}
divBuilder.InnerHtml = wrappedMessage + unorderedList.ToString(TagRenderMode.Normal);
if (formContext != null && !excludePropertyErrors)
{
// Inform the client where to replace the list of property errors after validation.
divBuilder.MergeAttribute("data-valmsg-summary", "true");
}
return divBuilder.ToHtmlString(TagRenderMode.Normal);
}
示例11: BuildValidationSummary
private IHtmlString BuildValidationSummary(string message, bool excludeFieldErrors, IDictionary<string, object> htmlAttributes)
{
IEnumerable<string> errors = null;
if (excludeFieldErrors)
{
// Review: Is there a better way to share the form field name between this and ModelStateDictionary?
var formModelState = ModelState[ModelStateDictionary.FormFieldKey];
if (formModelState != null)
{
errors = formModelState.Errors;
}
}
else
{
errors = ModelState.SelectMany(c => c.Value.Errors);
}
bool hasErrors = errors != null && errors.Any();
if (!hasErrors && (!UnobtrusiveJavaScriptEnabled || excludeFieldErrors))
{
// If no errors are found and we do not have unobtrusive validation enabled or if the summary is not meant to display field errors, don't generate the summary.
return null;
}
else
{
TagBuilder tagBuilder = new TagBuilder("div");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.AddCssClass(hasErrors ? ValidationSummaryClass : ValidationSummaryValidClass);
if (UnobtrusiveJavaScriptEnabled && !excludeFieldErrors)
{
tagBuilder.MergeAttribute("data-valmsg-summary", "true");
}
StringBuilder builder = new StringBuilder();
if (message != null)
{
builder.Append("<span>");
builder.Append(Encode(message));
builder.AppendLine("</span>");
}
builder.AppendLine("<ul>");
foreach (var error in errors)
{
builder.Append("<li>");
builder.Append(Encode(error));
builder.AppendLine("</li>");
}
builder.Append("</ul>");
tagBuilder.InnerHtml = builder.ToString();
return tagBuilder.ToHtmlString(TagRenderMode.Normal);
}
}
示例12: GenerateLabel
protected virtual HtmlString GenerateLabel([NotNull] ModelMetadata metadata,
string htmlFieldName,
string labelText,
object htmlAttributes)
{
var resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName;
if (resolvedLabelText == null)
{
resolvedLabelText =
string.IsNullOrEmpty(htmlFieldName) ? string.Empty : htmlFieldName.Split('.').Last();
}
if (string.IsNullOrEmpty(resolvedLabelText))
{
return HtmlString.Empty;
}
var tag = new TagBuilder("label");
tag.Attributes.Add(
"for",
TagBuilder.CreateSanitizedId(
ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName),
IdAttributeDotReplacement));
tag.SetInnerText(resolvedLabelText);
tag.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes), replaceExisting: true);
return tag.ToHtmlString(TagRenderMode.Normal);
}
示例13: GridLink
public static IHtmlString GridLink(WebGrid webGrid, string url, string text)
{
TagBuilder builder = new TagBuilder("a");
builder.SetInnerText(text);
builder.MergeAttribute("href", url);
if (webGrid.IsAjaxEnabled)
{
builder.MergeAttribute("data-swhglnk", "true");
}
return builder.ToHtmlString(TagRenderMode.Normal);
}
示例14: HttpMethodOverride
public MvcHtmlString HttpMethodOverride(string httpMethod)
{
if (String.IsNullOrEmpty(httpMethod))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "httpMethod");
}
if (String.Equals(httpMethod, "GET", StringComparison.OrdinalIgnoreCase) ||
String.Equals(httpMethod, "POST", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(MvcResources.HtmlHelper_InvalidHttpMethod, "httpMethod");
}
TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.Attributes["type"] = "hidden";
tagBuilder.Attributes["name"] = HttpHeaders.XHttpMethodOverride;
tagBuilder.Attributes["value"] = httpMethod;
return tagBuilder.ToHtmlString(TagRenderMode.SelfClosing);
}
示例15: GenerateValidationMessage
protected virtual HtmlString GenerateValidationMessage(string expression,
string message,
object htmlAttributes,
string tag)
{
var modelName = ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
if (string.IsNullOrEmpty(modelName))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, "expression");
}
var formContext = ViewContext.ClientValidationEnabled ? ViewContext.FormContext : null;
if (!ViewData.ModelState.ContainsKey(modelName) && formContext == null)
{
return null;
}
ModelState modelState;
var tryGetModelStateResult = ViewData.ModelState.TryGetValue(modelName, out modelState);
var modelErrors = tryGetModelStateResult ? modelState.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 builder = new TagBuilder(tag);
builder.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.
builder.AddCssClass((modelError != null) ?
ValidationMessageCssClassName :
ValidationMessageValidCssClassName);
if (!string.IsNullOrEmpty(message))
{
builder.SetInnerText(message);
}
else if (modelError != null)
{
builder.SetInnerText(ValidationHelpers.GetUserErrorMessageOrDefault(modelError, modelState));
}
if (formContext != null)
{
builder.MergeAttribute("data-valmsg-for", modelName);
var replaceValidationMessageContents = string.IsNullOrEmpty(message);
builder.MergeAttribute("data-valmsg-replace",
replaceValidationMessageContents.ToString().ToLowerInvariant());
}
return builder.ToHtmlString(TagRenderMode.Normal);
}