This line below causing error because TagBuilder.InnerHtml
is a read only property and you can't use +=
operator to assign HTML string:
div.InnerHtml += label.ToString();
What you should do is using AppendHtml()
against existing LabelFor
helper:
div.InnerHtml.AppendHtml(label);
Take note that .NET Core MVC doesn't use System.Web
namespace, it uses Microsoft.AspNetCore
parent namespace instead. You should try IHtmlContent
to build your own custom helper instead of MvcHtmlString
, by following these steps:
1) Include all using
statements provided below to enable IHtmlContent
and IHtmlHelper
instance.
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
2) Create your custom helper using Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper
as parameter instead of System.Web.Mvc.HtmlHelper
, shown in example below:
public static IHtmlContent CustomLabelFor<TModel, TProperty>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
string result;
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "form-group");
var label = helper.LabelFor(expression, new { @class = "control-label col-lg-1" });
div.InnerHtml.AppendHtml(label);
using (var sw = new System.IO.StringWriter())
{
div.WriteTo(sw, System.Text.Encodings.Web.HtmlEncoder.Default);
result = sw.ToString();
}
return new HtmlString(result);
}
Note: This example helper already tested in VS 2017, .NET Core 2.1.
Related issue:
Create Custom HTML Helper in ASP.Net Core