Wednesday, 18 December 2013

ASP.Net Razor

Reading User Input
Another important feature of dynamic web pages is that you can read user input.
Input is read by the Request[] function, and posting (input) is tested by the IsPost condition:
@{
var totalMessage = "";
if(IsPost)
    {
    var num1 = Request["text1"];
    var num2 = Request["text2"];
    var total = num1.AsInt() + num2.AsInt();
    totalMessage = "Total = " + total;
    }
}
<html>
<body style="background-color: beige; font-family: Verdana, Arial;">
<form action="" method="post">
<p><label for="text1">First Number:</label><br>
<input type="text" name="text1" /></p>
<p><label for="text2">Second Number:</label><br>
<input type="text" name="text2" /></p>
<p><input type="submit" value=" Add " /></p>
</form>
<p>@totalMessage</p>
</body>
</html>


Converting Data Types
Converting from one data type to another is sometimes useful.

The most common example is to convert string input to another type, such as an integer or a date.
As a rule, user input comes as strings, even if the user entered a number. Therefore, numeric input values must be converted to numbers before they can be used in calculations.
Below is a list of common conversion methods:

Method
Description
Example
AsInt()
IsInt()
Converts a string to an integer.
if (myString.IsInt())
  {myInt=myString.AsInt();}
AsFloat()
IsFloat()
Converts a string to a floating-point number.
if (myString.IsFloat())
  {myFloat=myString.AsFloat();}
AsDecimal()
IsDecimal()
Converts a string to a decimal number.
if (myString.IsDecimal())
  {myDec=myString.AsDecimal();}
AsDateTime()
IsDateTime()
Converts a string to an ASP.NET DateTime type.
myString="10/10/2012";
myDate=myString.AsDateTime();
AsBool()
IsBool()
Converts a string to a Boolean.
myString="True";
myBool=myString.AsBool();
ToString()
Converts any data type to a string.
myInt=1234;
myString=myInt.ToString();

No comments:

Post a Comment