你好,我必须将 MvcHtmlString 转换为字符串。我在这段代码之前使用过。(.net 框架)
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();
现在我正在开发 .net 核心,我在
div.InnerHtml += label.ToString();
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
请帮帮我。我必须使用这种方法或替代方法。我正在尝试建立一个表格。
最佳答案
下面这一行导致错误,因为 TagBuilder.InnerHtml
是只读属性,您不能使用 +=
运算符分配 HTML 字符串:
div.InnerHtml += label.ToString();
你应该做的是对现有的 LabelFor
助手使用 AppendHtml()
:
div.InnerHtml.AppendHtml(label);
请注意,.NET Core MVC 不使用 System.Web
命名空间,而是使用 Microsoft.AspNetCore
父命名空间。您应该按照以下步骤尝试 IHtmlContent
来构建您自己的自定义帮助器而不是 MvcHtmlString
:
1) 包括下面提供的所有using
语句以启用IHtmlContent
和IHtmlHelper
实例。
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
2) 使用 Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper
作为参数而不是 System.Web.Mvc.HtmlHelper
创建自定义助手,如下例所示:
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);
}
注意:此示例助手已在 VS 2017、.NET Core 2.1 中测试。
相关问题:
关于c# - .NET 核心 MvcHtmlString(TextboxFor, LabelFor).ToString() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53413899/