gpt4 book ai didi

c# - HtmlDecode 不能在 html 属性中使用 Razor MVC

转载 作者:行者123 更新时间:2023-11-30 20:03:14 25 4
gpt4 key购买 nike

我试图在 View 中使用 MVC4/Razor 在 html 中写 Márcia 这个词,但结果是错误的,如:

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

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

已经尝试了下面的所有命令,但是在 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 解码不起作用?如何让它发挥作用?

最佳答案

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

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

这是我的主页索引 View :

@model mvctestappweb.Models.HomeModel

@{
ViewBag.Title = "Index";
}

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

View 上的输出如下所示:

Márcia
Márcia

编辑:我明白了。问题是,一旦您将 RAW 放入 HTML <span>将 á 转换为 &#225; 的标记无论。我对此进行了很多尝试,但无法找到阻止这种情况发生的方法。因此,这里有两个可能适合您的解决方法:

(我知道这并不理想,但这是我能找到的最好的解决方法。)

我的 Controller 代码:

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)

View 上的输出如下所示:

1: Márcia
2: Márcia

我的 HTML 源代码如下所示:

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

关于c# - HtmlDecode 不能在 html 属性中使用 Razor MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15548599/

25 4 0
文章推荐: javascript - ReactJS:动态添加标签和内容到 react-dom 并重新加载它
文章推荐: c# - 可以设置RequestValidationMode ="2.0"页面级别吗?
文章推荐: javascript - 使用对象的 GraphQL 字段类型
文章推荐: c# - PCL - 对于某些目标,无法从 Func> 转换为 Func