c# - .NET 核心 MvcHtmlString(TextboxFor, LabelFor).ToString() 错误

标签 c# .net asp.net-mvc .net-core

你好,我必须将 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();

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

请帮帮我。我必须使用这种方法或替代方法。我正在尝试建立一个表格。

最佳答案

下面这一行导致错误,因为 TagBuilder.InnerHtml 是只读属性,您不能使用 += 运算符分配 HTML 字符串:

div.InnerHtml += label.ToString();

你应该做的是对现有的 LabelFor 助手使用 AppendHtml():

div.InnerHtml.AppendHtml(label);

请注意,.NET Core MVC 不使用 System.Web 命名空间,而是使用 Microsoft.AspNetCore 父命名空间。您应该按照以下步骤尝试 IHtmlContent 来构建您自己的自定义帮助器而不是 MvcHtmlString:

1) 包括下面提供的所有using 语句以启用IHtmlContentIHtmlHelper 实例。

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 中测试。

相关问题:

Create Custom HTML Helper in ASP.Net Core

关于c# - .NET 核心 MvcHtmlString(TextboxFor, LabelFor).ToString() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53413899/

相关文章:

c# - 返回带有模型和查询字符串的 View

c# - 软件架构与数据库设计 : One database/web application per each company or one database/web application for all companies?

c# - 包含项目对的匹配项

c# - FluentValidation - 值必须是可分配的;参数名称 : left

c# - Windows 10 中的鼠标滑动

c# - 返回一个可变长度的字符串数组

C#继承问题

c# - 扩展 C# .NET 应用程序 - 是否构建自定义脚本语言?

asp.net - ASP.NET MVC 5发布预编译问题

asp.net-mvc - UserManager.FindByNameAsync 在 ASP.NET MVC 中缓慢