问题
Hello i must convert MvcHtmlString to string. I was using before this code.(.net framework)
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "form-group");
var label = helper.LabelFor(expression, new { @class = "control-label col-lg-1" });
div.InnerHtml += label.ToString();
Now I am developing .net core and I get error at
div.InnerHtml += label.ToString();
Error Image
Returns a string that represent the current object. Reference to type 'HtmlString' claims it is defined in 'System.Web', but it could not be found. Module 'System.Web, Version=4.0.0.0, Culture=neutral, PublicyToken=b03f5f7f11d50a3a should be referenced
Please help me. I must use this method or alternative. I am trying build a form.
回答1:
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
回答2:
Have you tried this ?:
div.InnerHtml += label.ToHtmlString();
来源:https://stackoverflow.com/questions/53413899/net-core-mvchtmlstringtextboxfor-labelfor-tostring-error