问题描述
我有一个显示html标记的输入字段,也没有执行应做的事情。在这种情况下,请在两行中显示内容,而不显示html标记。 (就像只显示一样-如下所示。)
在用户输入“我的第一个编辑的评论”之后,在将其保存到表中之前,我在其前面加上了带有p标记的“用户名”。我这样做是为了使它随后通过输入标签显示要更新或通过div标签显示时,“我的第一个编辑的评论”转到第二行。它适用于显示,但不适用于输入标签中的编辑。
使用的模型中数据库表中的数据。
<p>reguser1</p>My first edited comment.
我有一个仅显示字段,该字段不显示html标签,并且执行标签应做的事情。
使用的模型中数据库表中的数据。
<p>reguser2</p>My first comment about this new blog site.
如何对输入字段进行编码以使其正确显示-“我的第一个编辑的评论”进入第二行?
我正在使用我在“仅显示”字段中使用的内容来解码HTML-使用“解码”来摆脱标记。
value="@Html.Raw(WebUtility.HtmlDecode(@blogComment.BlogCommentContent))"
我也尝试过-但出现错误:
<div class="form-control" id="@string.Format("{0}_{1}","inputEditComment",blogComment.BlogCommentId)" style="display: inline; margin-top: 27px; font-size: 13px; color: #9c9898;">
@Html.EditorFor(model => WebUtility.HtmlDecode(@blogComment.BlogCommentContent))
</div>
错误是:
system.invalidOperationException: 'Templates can be used only with field access,property access,single-dimension array index,or single-parameter custom indexer expressions.'
这是asp.net部分视图(并非全部):
@if (blogComment.UserId == blogComment.SignedInUserId)
{
@* Can edit the input field. *@
<input type="text" id="@string.Format("{0}_{1}",blogComment.BlogCommentId)" class="form-control" value="@Html.Raw(WebUtility.HtmlDecode(@blogComment.BlogCommentContent))" style="display: inline; margin-top: 27px; font-size: 13px; color: #9c9898;" />
<a href="" class="editComment" data-id="@blogComment.BlogCommentId">Save</a>
<a href="" class="deleteComment" data-id="@blogComment.BlogCommentId"> Delete</a>
}
else
{
@* display only. *@
<div style="margin-top: 27px; font-size: 13px; color: #9c9898;">
@Html.Raw(WebUtility.HtmlDecode(@blogComment.BlogCommentContent))
</div>
}
解决方法
您的代码正确。您可能会感到困惑,因为在输入标记中插入HTML无效,因为它只能接受字符串。您正在尝试在此处的代码中插入HTML:
<input type="text" id="@string.Format("{0}_{1}","inputEditComment",blogComment.BlogCommentId)" class="form-control" value="@Html.Raw(WebUtility.HtmlDecode(@blogComment.BlogCommentContent))" style="display: inline; margin-top: 27px; font-size: 13px; color: #9c9898;" />
这将不起作用,因为它仍将转换为字符串,这就是为什么您的输出结果是这样的:
如果您确实要插入HTML,请使用HTML编辑器,或者可以将其放在div
内,如下所示:
<div style="margin-top: 27px; font-size: 13px; color: #9c9898;">
@Html.Raw(WebUtility.HtmlDecode(@blogComment.BlogCommentContent))
</div>