bob
bob

Reputation: 2734

MVC 5 trouble on validating posted form inputs that are html encoded

I have a view model with a string property:

    [StringLength(10)]
    public string phone { get; set; }

In a view:

@Html.EditorFor(x => x.phone)

If I enter '+12' and submit, 'phone' is html encoded and a controller gets enter image description here , so I had to decode before saving to database:

HttpUtility.HtmlDecode(phone);

Is this a normal behavior?

Another problem is that entering '+123456789' fails string length checks because it is encoded.

How would you handle this?

EDIT:

My controller action looks like:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "phone")] MyViewModel vm)

EDIT2:

I was using custom template that was by default adding sanitizing module to ModelBinders in Application_Start() which was causing the trouble. As garryp pointed out, the framework takes care of it once I get rid of custom binder and a controller is getting exact string that user entered. I am not certain that encoding/decodings are actually happening on the entered string though..

Upvotes: 1

Views: 262

Answers (1)

garryp
garryp

Reputation: 5776

It shouldn't be necessary to HtmlDecode the value; the framework should take care of this. Generally you store un-encoded values in your database and only encode them on the UI (to prevent XSS attacks and the like).

I would check the following:

  1. Are you allowing the framework to resolve your model for you? ie do your Actions have the model in the signature or are you using Request.Form, or some similar mechanism?
  2. Have you encoded the value twice? It is decoded once when it comes back to the server.
  3. How are you passing the values back to the server? Are you passing a load of string flags in your controller Action?

Upvotes: 1

Related Questions