Why I get a different result with the same HtmlDecode() function?

后端 未结 2 600
忘了有多久
忘了有多久 2020-12-22 01:06

This is my code :

string myText = \"Wählen Sie bitte\";
string myTextDecoded = HttpUtility.HtmlDecode(myText);
Response.Write(myTextDecoded);
ddAdul         


        
2条回答
  •  有刺的猬
    2020-12-22 01:53

    Based on your updated question, I'm going to make a potentially incorrect assumption about your understanding.

    I'm guessing that you're looking at the HTML source and not understanding why the string is encoded in one place and unencoded in the other. The explanation is rather straightforward: server-side controls automatically encode their content while Response.Write writes raw output. There's a reason for this: server side controls often contain user input which is inherently unsafe, so it's automatically encoded to prevent cross-site scripting attacks, or in the less nefarious cases, user input merely breaking your page.

    By way of example, imagine if the list didn't encode the content and you did this:

    ddAdulti.Items.Add(new ListItem("", ""));
    ddAdulti.Items.Add(new ListItem("An actual valid value", ""));
    

    The net result would be that your markup would look something like this:

    
        
    
    

    As you can see, that's clearly broken. What you end up with depends on the interpreting browser, but is most likely an empty dropdown list.

    Now, since the controls do encode their content, the markup ends up being:

    
    

    and things work out nicely. :-)

    [edit]

    It occurs to me that from my example, it's probably not clear why you're seeing the behavior with a character like 'ä'. That's because many character encodings don't support umlauted letters, so for the control writers, it's probably easiest to simply encode all characters outside the 7-bit ASCII character set. :-)

    [edit 2]

    It's becoming clear to me that the original post doesn't actually describe the real problem. Apparently, what markzzz is trying to do is fetch unencoded HTML from the database and display it as-is for the client. There already exists a WebForms control for doing this: LiteralControl. It will display whatever you stick in it, unencoded.

    That said, there is no way that I know to embed that inside a DropDownList -- see my explanation of how the rendered HTML would break. However, if you merely want to display a list of items, but not necessarily a dropdown list, you can use a LiteralControl inside a Repeater or some such.

提交回复
热议问题