【问题标题】:HtmlDecode dont work using Razor MVC inside html attributeHtmlDecode 在 html 属性中使用 Razor MVC 不起作用
【发布时间】:2014-04-28 19:40:14
【问题描述】:

我正在尝试使用 MVC4 / Razor 在 html 中编写单词 Márcia,但结果是错误的,例如:

<span title="M&#225;rcia">Márcia</span> 

注意:标签SPAN内的单词打印输出正确,但模型(@Model.Name)的same property中的单词显示为字符编码@987654322 @

已经尝试了下面的所有命令,但是在 html 属性中应用时任何人都可以工作:

@Html.Raw(model.Name)

@Html.Raw(HttpUtility.HtmlDecode(model.Name))

@Html.Raw(Server.HtmlDecode(model.Name))

@HttpUtility.HtmlDecode(model.Name)

@Server.HtmlDecode(model.Name)

为什么在 html 属性中使用时 html 解码不起作用?如何让它发挥作用?

【问题讨论】:

  • model.Name 的值是什么。 @Html.Raw("Márcia")为我工作
  • 也提供一些查看代码
  • 尝试使用@HttpUtility.HtmlDecode(Html.DisplayFor(model =&gt; model.Name).ToString()) 并告诉我结果。

标签: c# asp.net asp.net-mvc asp.net-mvc-3 html-entities


【解决方案1】:

这对我有用。这是我的HomeController 代码:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new HomeModel();
        model.Name1 = "Márcia";
        model.Name2 = "M&#225;rcia";
        return View(model);
    }
}

这是我的主页索引视图:

@model mvctestappweb.Models.HomeModel

@{
    ViewBag.Title = "Index";
}

@Model.Name1
<br />
@Html.Raw(Model.Name2)

视图上的输出如下所示:

Márcia
Márcia

编辑:我明白了。问题是,只要将 RAW 放入 HTML &lt;span&gt; 标签,无论如何它都会将 á 转换为 &amp;#225;。我玩得很好,但无法找到阻止这种情况发生的方法。因此,这里有两个可能对您有用的解决方法:

(我知道这并不理想,但这是我能找到的最好的工作。)

我的控制器代码:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new HomeModel();
        model.Name = "Márcia";
        model.SpanHtml = "<span title='Márcia'>Márcia</span>";
        return View(model);
    }
}

这是我的看法:

@model mvctestappweb.Models.HomeModel

@{
    ViewBag.Title = "Index";
}

1: @Html.Raw("<span title=\"" + @Html.Raw(Model.Name) + "\">" + @Model.Name + "</span>")
<br />
2: @Html.Raw(@Model.SpanHtml)

视图上的输出如下所示:

1: Márcia
2: Márcia

我的 HTML 源代码如下所示:

1: <span title="Márcia">Márcia</span>
<br />
2: <span title='Márcia'>Márcia</span>

【讨论】:

  • 您好,它也对我有用,因为第二个属性位于 html 标记之外。请尝试将 Model.Name2 放入 html 属性中,例如 。错误仍然存​​在
  • @jmrnet 我有一个带有文档列表的 Viewbag,其中一个文档的名称为“test1>test2”。我的 html 看起来像 @Html.DropDownList("Documents", (SelectList)ViewBag.Documents, "--Select Document--") 当它在显示为 test2>test1 的下拉列表“test1>test2”中运行时。我该怎么办?
【解决方案2】:

您可以将属性名称与值放在一起。

@{  
    var title = "title='Márcia'";  
}  

<span @Html.Raw(title)>Márcia</span> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多