Monday, April 7, 2014

Conversion Helpers in MVC Razor: Validating Posted Data

If you have worked with the .NET Framework for any amount of time, you must have encountered the term Validation. Validation is a way to post your data secure and in a required (acceptable) format. So that 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 particular 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 are broken into 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 that “string” is a default value for all type of request value. Whatever page submit it consider as string and later we have to cast in the required type.

These methods help to convert these values to appropriate type.

e.g. Suppose we have value as “1507”, which is of string type, though we can convert it as “int” using “1507”.AsInt().it’ll convert it into Numeric value.


These methods also give you privilege to convert the value on demand. For an e.g. if it attempts to parse the string value "Sachin Kalia" will fail, but if you provide a default value as a parameter to the .AsInt() method, it will return that value Instead:

int Id = Request["Name"].AsInt(55)

bool Name = Request["Age"].AsBool();

Kindly have a look at the depicted image below.


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 on the inbuilt extension methods which Razor offers in below depicted image.


You can have a look on the sample application which I’ve attached.These are the steps to reach upto the EditPost.cshtml page.

Step1. Run sample application .Press F5


Step2. Click on Edit button, it will redirect you to Edit.cshtml page.Fill the required details and press save button as shown in below image.


It reaches to page EditPost.cshtml and you can see it has value of Id as 55 rather than “Sachin”.


Hope you enjoyed and it may help you down the line.

Keep coding and Smile Smile


Post a Comment