Conversion Helpers in MVC Razor: Validating Posted Data

If you have worked with the .NET Framework for any amount of time then you must have encountered the term "validation". Validation is a way to post your data securely and in a required (acceptable) format. So that it could be easier to maintain.

Accepting and storing invalid data can often be more detrimental than not accepting any data at all. On the web, form posts are the primary way that data is exchanged between users and applications. Most data collected from users has some sort of requirements placed on it, validating that the data meets certain expectations before the application does anything with it. Validation can be as simple as requiring that a form field not be empty, that the field be a certain type or that a value falls within a specific range. Since form validation is so ubiquitous, most mature web application frameworks offer some way to express and evaluate business rules against posted form data.

In MVC validation is broken into the two groups: string conversion helpers and type verification helpers. Here I’ll elaborate more on Conversation Helpers.

The methods AsBool(), AsDateTime(), AsDecimal(), AsFloat(), and AsInt() attempt to parse values of the respective type from string variables.

As we know, “string” is a default value for many types of request values. Whatever the page submits is considered to be a string and later we need to cast it to the required type.

These methods help to convert these values to an appropriate type.

For example suppose we have the value “1507”, that is of a string type, though we can convert it to “int” using “1507”.AsInt(). It’ll convert it to a numeric value, as in the following:

Request["Age"].AsInt()

These methods also provide you the ability to convert the value on demand. For example if it attempts to parse the string value "Sachin Kalia" then it will fail, but if you provide a default value as a parameter to the .AsInt() method then it will return that value instead as in the following:

int Id = Request["Name"].AsInt(55)
bool Name = Request["Age"].AsBool();

Kindly have a look at the following image:



The specific extension method shows a message “converts a string to an Integer and specifies a default value” with an overloaded method.

Please have a look at the builtin extension methods that Razor offers in the following image.




You can have a look at the sample application that I’ve attached. This is the procedure to reach up to the "EditPost.cshtml" page.

Step 1: Run the sample application; press F5.



Step 2: Click on the Edit button, it will redirect you to the "Edit.cshtml" page. Fill in the required details and press the "Save" button as shown in the following image.




It reaches the "EditPost.cshtml" page and you can see that Id has the value 55 rather than “Sachin”.



I hope you enjoyed and it may help you down the line.

Keep coding and Smile.