Encoding of special characters before going to the SQL database

2

I'm working with SQL Server 2008 and IIS7 to host my MVC website.

For security reasons, the website on which I work at this time does not allow strings with special characters like '<' or '>' from <textarea> are sent to the database.

How can I encode these characters and then decode them after fetching the string from the database? I want to be able to do something like:

  • Encode special characters in RazorView into a string using JavaScript
  • Send the encoded string (which does not have the special characters) using a POST to the Controller of the MVC
  • Search the string for the database and also decode the view
  • asked by anonymous 28.03.2017 / 16:54

    2 answers

    3

    You do not need any of this. Just mark the Model or ViewModel with [AllowHtml] :

    [AllowHtml]
    [DataType(DataType.MultilineText)]
    public String MeuTextoHtml { get; set; }
    
        
    28.03.2017 / 19:05
    0

    HTML

    First implement the function below, to create an element and get your html

    function HtmlEncode(s)
    {
        var el = document.createElement("div");
        el.innerText = el.textContent = s;
        s = el.innerHTML;
        el.remove();
        return s;
    }
    

    Then in your POST you encode the string and send

    var conteudo=HtmlEncode($("#MinhaTextArea").val())
    $.ajax({
        url: '/Meucontrole/MinhaAction',
        method:"Post",
        data:{parametro:conteudo},
        success: function (d) {
            //TODO:;
        }
    
    })
    

    Controller

    In your controler you will receive the string encoded in the parametro parameter, to decode use System.Web.HttpUtility.HtmlDecode() and to code again System.Web.HttpUtility.HtmlEncode(t) .

    [HttpPost]
    public ActionResult MinhaAction(string parametro)
    {
        var decodificado = System.Web.HttpUtility.HtmlDecode(parametro);
    
        //TODO:;
    
        var codificado = System.Web.HttpUtility.HtmlEncode(decodificado);
        return View();
    }
    
        
    28.03.2017 / 18:13