2012-07-26 21 views
21

In primo luogo, voglio far sapere a tutti che sto usando un motore aspx non un motore Razor.Come posso consentire l'invio di tag HTML in una casella di testo in asp.net?

Ho una tabella all'interno di un modulo. Un mio testo contiene i tag HTML come

</br>Phone: </br> 814-888-9999 </br> Email: </br> [email protected] 

Quando vado a costruirlo esso mi dà un errore che dice

Un valore potenzialmente pericoloso Request.Form è stato rilevato dal client (QuestionAnswer="...ics Phone:<br/>814-888-9999<br...").

Ho provato la richiesta di convalida = "false" ma non ha funzionato.

Mi dispiace non ho aggiunto il mio codice html per voi per guardare fino ad ora. Sto tirando una domanda su dove posso modificarlo, se necessario.

<%@ 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> 

risposta

23

prima che la pagina viene sottoposta è necessario html codifica il valore della casella di testo, con window.escape (...)

Se è necessario il testo senza escape sul lato server, utilizzareMetodo.

campione molto veloce:

<%@ 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> 

apportare queste modifiche al codice:

<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> 
+0

Ho aggiunto il mio html per mostrarvi ciò che avevo originariamente – Yusuf

+0

Funziona Perfetto per me grazie! – Krismorte

1

utilizzando HTML in testo non è una buona pratica, magari utilizzare le interruzioni di linea (Environment.NewLine) o \ r \ n al posto di br? .NET Reference

Esempio (in C#):

textBox1.Multiline = true; 
textBox1.Text = "test" + Environment.NewLine + "test2"; 
+0

posso usare che nella casella di testo// n o/r? – Yusuf

+0

Ho inserito il \ n nella casella di testo che non ha funzionato. Non mi ha dato neanche un errore. è appena immesso il \ n così ora è come \ n814-888-9999 – Yusuf

+0

@Yusuf se il tipo della casella di testo è multilinea, lo fa! Usa text1.text = "test" + "\ r \ n" + "test2"; – XhkUnlimit

4

decorare la vostra azione di controllo con l'attributo [ValidateInput]:

[ValidateInput(false)] 
[HttpPost] 
public ActionResult Foo(MyViewModel model) 
{ 
    ... 
} 
+10

-1: Sebbene questa sia una risposta valida, non è buona.Non penso che sia una buona idea suggerire che gli utenti debbano disabilitare ciecamente la convalida. Invece, dovrebbero determinare che _why_ la validazione non sta funzionando e quindi trovare una soluzione che non spenga solo un importante meccanismo di sicurezza. Suggerimenti come quelli forniti da [Ted Spence] (http://stackoverflow.com/a/11673224/56864) e [Adrian] (http://stackoverflow.com/a/11673254/56864) sono un buon punto di partenza. –

+0

@KevinBabcock, * importante meccanismo di sicurezza *? Rido di quello. Potresti spiegare cosa è tanto importante in questa convalida? Inoltre stai disabilitando la convalida solo per questa particolare azione. In ASP.NET MVC 3 è possibile ottenere anche una logica più fine grazie alla decorazione delle proprietà del modello di vista con l'attributo '[AllowHtml]'. Qual è il punto di usare javascript per sfuggire all'input dell'utente prima di inviarlo? –

+5

Seriamente? Stai sostenendo che la validazione dell'input è ridicola e non importante? "La neutralizzazione impropria" dell'input dell'utente è [elencata nelle prime 3 delle 25 principali vulnerabilità di sicurezza del software oggi] (http://www.sans.org/top25-software-errors/). Hai appena detto al tizio di disabilitare la convalida dell'input senza alcuna spiegazione. Nessuna spiegazione, nessuna alternativa, niente. –

3

client JavaScript:

function codificarTags() { 
        document.getElementById('txtDescripcion').value = document.getElementById('txtDescripcion').value.replace(/</g,'&lt;').replace(/>/g,'&gt;'); 
      }; 

<form id="form1" runat="server" onsubmit="codificarTags();"> 

Server:

protected void Page_Load(object sender, EventArgs e) 
    { 
     txtDescripcion.Text = txtDescripcion.Text.Replace(@"&lt;", @"<").Replace(@"&gt;", @">"); 
Problemi correlati