Декодируйте HTML-тег, чтобы его можно было прочитать, когда он возвращается на сервер, а точнее на контроллер.

Мой движок Aspx.

Как я могу декодировать/кодировать теги html, которые находятся в моем текстовом поле. У меня есть html-тег
, чтобы сделать его более читаемым. Я пробовал ValidationRequest и htmlDecode(freqQuestion.Answer), но не повезло. Я просто продолжаю получать одно и то же сообщение.

Ошибка сервера в приложении «/Администратор».

A potentially dangerous Request.Form value was detected from the client (QuestionAnswer="...ics Phone:
123-456-7890

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. To allow pages to override application request validation settings, set the requestValidationMode attribute in the httpRuntime configuration section to requestValidationMode="2.0". Example: . After setting this value, you can then disable request validation by setting validateRequest="false" in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case. For more information, see http://go.microsoft.com/fwlink/?LinkId=153133.

View Page

  <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" validateRequest="false" 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.DarkstarAdminProductionServices.FreqQuestionsUser freqQuestionsUser = ViewBag.freqQuestionsUser != null ? ViewBag.freqQuestionsUser : new Administrator.DarkstarAdminProductionServices.FreqQuestionsUser(); %>
<%List<string> UserRoleList = Session["UserRoles"] != null ? (List<string>)Session["UserRoles"] : new List<string>(); %>
<form id="updateFreqQuestionsUser" action="<%=Url.Action("SaveFreqQuestionsUser","Prod")%>" method="post">
    <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="<%=Server.HtmlDecode(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>

Контроллер

  [AuthorizeAttribute(AdminRoles = "EditFreqQuestionsUser")]
    public ActionResult SaveFreqQuestionsUser(string QuestionDescription, string QuestionAnswer)
    {
        Guid freqQuestionsUserId = Request.Form["freqQuestionsUserId"] != null ? new Guid(Request.Form["freqQuestionsUserId"]) : Guid.Empty;


        //load agreement eula ref
        AdminProductionServices.FreqQuestionsUser freqqQuestionsUser = Administrator.Models.AdminProduction.FreqQuestionsUser.LoadFreqQuestionsUser(freqQuestionsUserId, string.Empty, string.Empty)[0];

        freqqQuestionsUser.questionDescription = QuestionDescription;
        freqqQuestionsUser.questionAnswer = QuestionAnswer;

        //save it
               Administrator.Models.AdminProduction.FreqQuestionsUser.addFreqQuestionsUser(freqqQuestionsUser);

        return RedirectToAction("SearchFreqQuestionsUser", "Prod", new { FreqQuestionsUserId = freqQuestionsUserId });
    }

person Yusuf    schedule 02.08.2012    source источник
comment
К вашему сведению, <td colspan="2" class="label">Question Description:</td> должно быть <td colspan="2" class="label"><label for="QuestionDescription">Question Description:</label></td>, а <input type="text" maxlength="2000" name="QuestionDescription" value="<%=freqQuestionsUser.questionDescription%>" /> должно быть <input type="text" maxlength="2000" name="QuestionDescription" value="<%=freqQuestionsUser.questionDescription%>" id="QuestionDescription" />. В заключение я добавил <label for="QuestionDescription">Question Description</label> и добавил к входу id="QuestionDescription".   -  person David Bélanger    schedule 02.08.2012
comment
Какая основная разница? просто любопытно   -  person Yusuf    schedule 02.08.2012
comment
Немного. Просто добавил настоящий ярлык. Когда вы нажмете на текст, он автоматически сфокусирует ввод. Просто дружелюбная вещь, которую должен иметь каждый веб-сайт...   -  person David Bélanger    schedule 02.08.2012
comment
@Jeremy: не так много защиты, любой может заглянуть в историю :-)   -  person Fyodor Soikin    schedule 02.08.2012
comment
@Jeremy: Сказать, что это, вероятно, привлекло гораздо больше внимания к номеру телефона, чем просто сделать это тихо. ;-)   -  person Chris    schedule 02.08.2012
comment
Пожалуйста, не удаляйте содержание вашего вопроса после того, как на него уже был дан ответ.   -  person Bill the Lizard    schedule 27.09.2012


Ответы (1)


Директива ValidateRequest не работает с MVC, потому что, в отличие от WinForms, файл .aspx не является сущностью, которая получает запрос. Контроллер есть. Следовательно, контроллер — это то место, где вы должны отключить проверку. Просто примените атрибут [ValidateInput (false)] к вашему действию или ко всему контроллеру, и среда выполнения пропустит ваши теги.

person Fyodor Soikin    schedule 02.08.2012