在线描述 http://www.mikesdotnetting.com/article/275/custom-taghelpers-in-asp-net-mvc-6如何创建分页标记帮助器。
下面的行
a.InnerHtml = i.ToString ();
li.InnerHtml = a.ToString ();
不起作用。
Error : CS0200 C# Property or indexer 'TagBuilder.InnerHtml' cannot be assigned to -- it is read only
也行
[TargetElement("pager", Attributes = "total-pages, current-page, url")]
有错误 旧的分页选项很容易设置,并且工作正常......但新版本是实施线索
答案 0 :(得分:0)
我已经解决了这个问题:
using Microsoft.AspNet.Razor.TagHelpers;
using Microsoft.AspNet.Mvc.Rendering;
using System.Text;
using Microsoft.Extensions.WebEncoders;
namespace MVC6_CustomTagHelper_Demo.TagHelpers
{
[HtmlTargetElement("pager", Attributes = "total-pages, current-page, link-url")]
public class PagerTagHelper : TagHelper
{
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
[HtmlAttributeName("link-url")]
public string Url { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div";
output.PreContent.SetHtmlContent("<ul class=\"link-list\">");
var items = new StringBuilder();
for (var i = 1; i <= TotalPages; i++)
{
var li = new TagBuilder("li");
var a = new TagBuilder("a");
a.MergeAttribute("href", $"{Url}?page={i}");
a.MergeAttribute("title", $"Click to go to page {i}");
a.InnerHtml.AppendHtml(i.ToString());
if (i == CurrentPage)
{
a.AddCssClass("active");
}
li.InnerHtml.Append(a);
var writer = new System.IO.StringWriter();
li.WriteTo(writer, new HtmlEncoder());
var s = writer.ToString();
items.AppendLine(s);
}
output.Content.SetHtmlContent(items.ToString());
output.PostContent.SetHtmlContent("</ul>");
output.Attributes.Clear();
output.Attributes.Add("class", "pager");
}
}
}
答案 1 :(得分:0)
InnerHtml
不再有setter,但它现在拥有方法Append
,AppendLine
,AppendFormat
,AppendHtml
和AppendHtmlLine
。您可以使用它们将字符串直接注入TagBuilder
。
如果您正在扩展Html
Razor指令(因此@Html.MyMethod('foo')
),第一个特别有用,因为您可以挂钩任何其他Html
方法,例如部分。
示例 - 为角度js模板创建实用程序扩展,转换
@Html.AngularTemplate("FooBar")
进入
<script type="text/ng-template" id="foo-bar.html">{{Content of FooBar.cshtml}}</script>
因此 -
using Microsoft.AspNet.Html.Abstractions;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Extensions.WebEncoders;
using System;
using System.Text.RegularExpressions;
...
public static object AngularTemplate(this IHtmlHelper helper, string templateName)
{
var tagBuilder = new TagBuilder("script");
tagBuilder.MergeAttribute("type", "text/ng-template");
// turn CamelCase into camel-case
tagBuilder.MergeAttribute("id", Regex.Replace(templateName, @"([a-z])([A-Z])", "$1-$2").ToLowerInvariant() + ".html");
tagBuilder.InnerHtml.AppendHtml(helper.Partial(templateName));
tagBuilder.TagRenderMode = TagRenderMode.Normal;
tagBuilder.WriteTo(helper.ViewContext.Writer, HtmlEncoder.Default);
return null;
}