Search code examples
c#asp.net-mvcmaskedinput

What is the best pratice to change a field value when a form is submitted in MVC?


I have a lot of fields in my View that are masked with jquery MaskedInput. They're masked because the user need to see it with a mask, but I need to remove these masks before commiting the value in my database.

I don't want to mess up the code, since this is one of the most importants Views in my project.

So what's the best pratice to do this?

Suppose I have this Model:

public class MyViewModel {
    public string MyMaskedProperty { get; set;}
}

And this code in View:

@Html.TextboxFor(x=> x.MyMaskedProperty, new { @class="myMask"} )

Should I:

  1. Remove the mask on my View, using javascript, before the form is subimitted
  2. Remove the mask on my Model, changing the get of MyMaskedProperty to return an unmasked value
  3. Remove the mask on my Controller, since it need to be unmasked only from here and beyond
  4. Something better than the 3 solutions above.

Thanks in advance!


Solution

  • Similar to the second option, you might simply add a read-only field to your view model:

    public class MyViewModel {
        public string MyMaskedProperty { get; set;}
    
        public string MyUnmaskedProperty
        {
            get
            {
                // return an "unmasked" version of MyMaskedProperty
            }
        }
    }
    

    Even if you were to modify the value with JavaScript, you can't really implicitly trust that and would want to validate server-side anyway. And doing it in the controller isn't ideal because that's just procedural code that would need to be repeated all over the place. Following the advice to "keep your controllers light and your models heavy", this logic really belongs on the model.

    The model itself can be constructed from any version of the data, really. As long as the information used to construct the model can effectively construct it, then the model can expose all sorts of operations and properties for manipulating and viewing that information.