简体   繁体   中英

Is this how you properly encode html textarea in csharp

I'm trying to add a function to encode a text area into my Case switch statement as well as decoding it on Submit. I came as close as this code below but the function part of the encoding appears to have been written wrong according to visual studio. Any help would be appreciated, thank you!

Encoding part of code -

case FieldType.EncodedTextarea:
        string encodedtextareaDefaultValue = this.Model.DefaultValue;
        if (!string.IsNullOrWhiteSpace(this.Model.FieldValue))
        {
            encodedtextareaDefaultValue = this.Model.FieldValue;
        }

        <textarea id="@this.Model.FieldKey" name="@this.Model.FieldKey" class="form-control hidden-print encoded" @Html.Raw(validationAttributes)
                  placeholder="@this.Model.PromptText" rows="5">@encodedtextareaDefaultValue</textarea>
        <span class="print-view">
            @encodedtextareaDefaultValue
        </span>

        <script type="text/javascript">
        function htmlEncode(str) {
        return string encoded = str.Replace('&', '&amp;').Replace(''<'', '&lt;').Replace(''>'', ''&gt;'').Replace('\', '&quot;'').Replace('''', '&apos;');
        }
        </script>
        break;

Decoding part of code -

$.each($('#recordForm input:not(:radio, :checkbox), #recordForm select, #recordForm textarea, .k-file-name'), function (i, v) {
            if (v.type !== 'submit') {
                if ($(v).hasClass('k-file-name')) {
                    data['FileName'] = $(v).text();
                }
                if(v.hasClass('encoded')){
                    data[v.name] = String(v.value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
                }
                data[v.name] = v.value;
            }
        }); //end each

You can use inbuilt methods like htmlencode and htmldecode which are available in http utility.

When you submit the textbox check whether its empty or not. If its not empty send the data to submit function and do HTML encode. While retrieving the data use HTML decode. Please refer below link. https://docs.microsoft.com/en-us/dotnet/api/system.web.httputility.htmlencode?view=netcore-3.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM