Как включить HTML-теги в текстовое поле в asp.net?
Во-первых, я хочу сообщить всем, что я использую движок aspx, а не движок Razor.
У меня есть таблица в форме. Одно из моих текстовых полей содержит теги html, например
</br>Phone: </br> 814-888-9999 </br> Email: </br> [email protected]
Когда я иду, чтобы создать его, он дает мне сообщение об ошибке
От клиента (QuestionAnswer="...ics Phone:<br/>814-888-9999<br...")
было обнаружено потенциально опасное значение Request.Form.
Я попробовал запрос проверки = "false", но это не сработало.
Мне жаль, что я не добавил свой html-код, чтобы вы могли посмотреть до сих пор. Я задаю вопрос, где я могу его отредактировать, если потребуется.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
EditFreqQuestionsUser
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$("#freqQuestionsUserUpdateButton").click(function () {
$("#updateFreqQuestionsUser").submit();
});
});
</script>
<h2>Edit Freq Questions User </h2>
<%Administrator.AdminProductionServices.FreqQuestionsUser freqQuestionsUser = ViewBag.freqQuestionsUser != null ? ViewBag.freqQuestionsUser : new Administrator.AdminProductionServices.FreqQuestionsUser(); %>
<%List<string> UserRoleList = Session["UserRoles"] != null ? (List<string>)Session["UserRoles"] : new List<string>(); %>
<form id="updateFreqQuestionsUser" action="<%=Url.Action("SaveFreqQuestionsUser","Prod")%>" method="post" onsubmit+>
<table>
<tr>
<td colspan="3" class="tableHeader">Freq Questions User Details <input type ="hidden" value="<%=freqQuestionsUser.freqQuestionsUserId%>" name="freqQuestionsUserId"/> </td>
</tr>
<tr>
<td colspan="2" class="label">Question Description:</td>
<td class="content">
<input type="text" maxlength="2000" name="QuestionDescription" value=" <%=freqQuestionsUser.questionDescription%>" />
</td>
</tr>
<tr>
<td colspan="2" class="label">QuestionAnswer:</td>
<td class="content">
<input type="text" maxlength="2000" name="QuestionAnswer" value="<%=freqQuestionsUser.questionAnswer%>" />
</td>
</tr>
<tr>
<td colspan="3" class="tableFooter">
<br />
<a id="freqQuestionsUserUpdateButton" href="#" class="regularButton">Save</a>
<a href="javascript:history.back()" class="regularButton">Cancel</a>
</td>
</tr>
</table>
</form>
</asp:Content>
Ответы
Ответ 1
перед отправкой страницы вам нужно html закодировать значение текстового поля, используя window.escape(...)
Если вам нужен неэкранированный текст на стороне сервера, используйте метод HttpUtility.UrlDecode(...)
.
очень быстрый образец:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SO.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function makeSafe() {
document.getElementById('TextBox1').value = window.escape(document.getElementById('TextBox1').value);
};
function makeDangerous() {
document.getElementById('TextBox1').value = window.unescape(document.getElementById('TextBox1').value);
}
</script>
</head>
<body>
<form id="form1" runat="server" onsubmit="makeSafe();">
<div>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Rows="10" ClientIDMode="Static"></asp:TextBox>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
<script>
makeDangerous();
</script>
</body>
</html>
Внесите эти изменения в свой код:
<script type="text/javascript">
$(document).ready(function () {
makeDangerous();
$("#freqQuestionsUserUpdateButton").click(function () {
makeSafe();
$("#updateFreqQuestionsUser").submit();
});
});
// Adding an ID attribute to the inputs you want to validate is simplest
// Better would be to use document.getElementsByTagName and filter the array on NAME
// or use a JQUERY select....
function makeSafe() {
document.getElementById('QuestionAnswer').value = window.escape(document.getElementById('QuestionAnswer').value);
};
// In this case adding the HTML back to a textbox should be 'safe'
// You should be very wary though when you use it as actual HTML
// You MUST take steps to ensure the HTML is safe.
function makeDangerous() {
document.getElementById('QuestionAnswer').value = window.unescape(document.getElementById('QuestionAnswer').value);
}
</script>
Ответ 2
Украсьте действие вашего контроллера с помощью атрибута [ValidateInput]
:
[ValidateInput(false)]
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
...
}
Ответ 3
Клиентский JavaScript:
function codificarTags() {
document.getElementById('txtDescripcion').value = document.getElementById('txtDescripcion').value.replace(/</g,'<').replace(/>/g,'>');
};
<form id="form1" runat="server" onsubmit="codificarTags();">
Сервер:
protected void Page_Load(object sender, EventArgs e)
{
txtDescripcion.Text = txtDescripcion.Text.Replace(@"<", @"<").Replace(@">", @">");
Ответ 4
Использование html в текстовом поле не является хорошей практикой, может быть, использовать linebreaks (Environment.NewLine
) или \r\n вместо br
?
. Ссылка NET
Пример (в С#):
textBox1.Multiline = true;
textBox1.Text = "test" + Environment.NewLine + "test2";
Ответ 5
Я бы предложил использовать HTML-редактор AjaxControlToolkit. Я реализую это сейчас. Если вы текстовое поле многострочное и достаточно большое для размещения HTML, почему бы не просто поднять его на HTML-редактор. Ваш пользователь тоже будет счастлив.
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HTMLEditor/HTMLEditor.aspx