How to use while Loop in C#
Hello friends, I hope you all are great. Today, I am posting 10th tutorial in C# series and its about How to use while Loop in C#. It's gonna be a quick tutorial, as there's not much to discuss.
In our 8th tutorial in C# series, we have had a look at
How to use IF Loop in C# and we have seen that IF loop takes a Boolean expression and if it's TRUE then it allows the compiler to enter in it just once. While loop is quite similar to IF loop as it takes a Boolean expression as well but it will keep on executing again & again, so let's have a look at it in detail:
How to use while Loop in C#
- While Loop in C# takes a Boolean expression as a condition and it will keep on executing as long as the conditional expression returns true, we can say Execute while condition is TRUE.
- Here's the syntax of while loop:
while (Boolean Expression)
{
// Code will execute, while Boolean Expression is TRUE
}
- So, let's design a simple example to understand How while Loop works:
- In schools, you must have studied math tables, so I have created a simple code using while loop which asks from the user to enter table of.
- When user enters the number, the program will print out its table till 10.
- If you look at the code, I have used while loop and this while loop will execute 10 times as the condition in while loop is TotalLength <= 10.
- I have incremented this TotalLength variable in while Loop so when it will become 10, the while loop will stop.
- So, instead of writing 10 lines to display table, we are just using while loop, we can also increase the lines to 20 or 30 quite easily, that's the benefit of while loop.
- Let's play with the code a little and print values till 20 and also use IF Loop in this while loop, which we have studied in 8th lecture.
- You can see in above code that I have increased the length to 20 and then in while Loop, I have used IF Loop.
- IF the length is 10 then I am just adding blank lines to separate first 10 from last 10.
- I hope you got the idea of How to use While Loop and what's its difference from IF Loop, the IF Loop executed just once when condition comes true.
- Here's the complete code used in today's lecture:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Table of : ");
int TableOf = int.Parse(Console.ReadLine());
int TotalLength = 1;
while (TotalLength <= 20)
{
int TableValue = TotalLength * TableOf;
Console.WriteLine("{0} x {1} = {2}", TableOf, TotalLength, TableValue);
if(TotalLength==10)
{
Console.WriteLine("\n");
}
TotalLength++;
}
Console.WriteLine("\n\n");
}
}
}
So, that was all about How to use while Loop in C#. In our coming tutorial, we will have a loop at How to use do While Loop in C#. Till then take care !!! :)
How to use switch Statement in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at How to use switch Statement in C# and its our 9th tutorial in C# series. In our previous tutorial, we have seen
IF Loop in C# and this switch statement is also a loop but works slightly different than IF loop and it totally depends on your application, which one you want to use.
First we will have a look at How to use switch statement in C# and after that we will also study goto statement, because switch and goto statements are normally used together. So, let's get started with it:
How to use switch Statement in C#
- Switch Statement is a loop in C# which takes a variable as a condition, and then creates its different cases and we can deal each case separately.
- We need to use break Statement after every case Statement to get out of the switch Statement.
- We can also use default Statement at the end of switch Statement, which will execute if none of the cases are true.
- So let's have a look at the syntax of switch statement in C#:
switch (variable) {
case value1:
// This case will execute, if variable = value1
break;
case value2:
// This case will execute, if variable = value2
break;
.
.
.
case valueN:
// This case will execute, if variable = valueN
break;
default:
// default will execute, if all the above cases are false.
break;
}
- As you can see in above syntax, we have first used switch keyword and then took a variable, this variable can have any datatype.
- Then we have created different cases, we can create as many cases as we want and each case has a value so if the variable is equal to that value then respective case will execute.
- Let's understand it with an example: Let's design a project where we display information of class students using their roll number, so we will take their roll numbers as an input and will display the respective student's data using switch case statement:
- As you can see in the above figure that I have first asked for the student's Roll Number and then placed a switch statement and provided RollNo as a conditional variable.
- After that in each case I have placed the roll no value and for each roll number I have added the name and age of the user.
- In execution, I have entered 1 and the code has provided me data placed in case 1 and have ignored all the other cases as well as the default case.
- But if you run this code then you will realize that it asks for the Roll number only once but what if we want it to run again & again.
- We can use goto Statement for that purpose, although it's not the best way to create loop but one of the ways and you should know about it.
- In above code, I have just added two lines of code, first I have placed a tag Start: at the top of the code and then at the end I have used goTo Start;
- So, at the goto Statement, the compiler will find the tag mentioned and will move on to that position and will start executing the code, so it's kind of an infinite loop which is never gonna stop.
- Here's the final code, which you can test in visual studio:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Start:
Console.Write("Please enter student's roll number: ");
int RollNo = int.Parse(Console.ReadLine());
switch(RollNo)
{
case 1:
Console.WriteLine("Name: StudentA");
Console.WriteLine("Age: 18");
break;
case 2:
Console.WriteLine("Name: StudentB");
Console.WriteLine("Age: 17");
break;
case 3:
Console.WriteLine("Name: StudentC");
Console.WriteLine("Age: 16");
break;
case 4:
Console.WriteLine("Name: StudentD");
Console.WriteLine("Age: 20");
break;
case 5:
Console.WriteLine("Name: StudentE");
Console.WriteLine("Age: 21");
break;
default:
Console.WriteLine("No student found.");
break;
}
Console.WriteLine("\n\n");
goto Start;
}
}
}
So, that was all about How to use switch Statement in C#. If you need any help then ask in comments. Will meet you in next tutorial. Till then take care !!! :)
How to use IF Loop in C#
Hello everyone, I hope you all are doing great. Today, we are gonna have a look at IF Loops in C# and it's 8th tutorial in C# series. So far, we have discussed some basic concepts in C# and now we are ready to get our hands on Loops in C#.
C#, as any other programming language, supports a lot of loop structures, we will discuss each one of them separately in our coming tutorials. Today, we will discuss the simplest of them all, which is IF loop, so let's get started with How to use IF Loop in C#:
How to use IF Loop in C#
- IF Loop in C# takes a Boolean expression as a condition and if this condition is TRUE, the compiler executes the code inside IF loop { } and if the condition is wrong, the compiler simply ignores the code.
- Here's the syntax of IF Loop in C#:
if (boolean-expression)
{
// Code will come here, execute if the Condition is TRUE.
}
- Let's create a simple program, where we ask the user to enter his Physics marks and the program will tell the user whether he is passed or failed.
- I have used If loop and the condition I have used is, if the marks are less than 50 then student has failed & if its equal or greater than 50 then the user has passed.
- Here's the code for IF loop in C#, shown in below figure:
- You can see in above figure that I have entered 25, now when the compiler will come to first IF loop, it will check the condition (Marks >= 50), which is not true as the number we entered is less than 50, so the compiler will simply ignore this IF loop and will move on to second IF Loop.
- The condition in second IF Loop is (Marks < 50), and clearly this condition is TRUE, so our compiler will enter in this IF Loop, enclosed by curly brackets { }, and will print out "You failed the exam.".
- So, in simple words:
- IF condition is TRUEÂ => Execute.
- IF condition is FALSE => Ignore.
- Few commonly used conditional operators of IF Loops are:
- Equal to ( == )
- Not Equal to ( != )
- Greater than ( > )
- Less than ( < )
- Greater than or Equal to ( >= )
- Less than or Equal to ( <= )
- We could also use multiple conditions in single IF Loop using these two operators:
- && ( AND ) => it returns TRUE, if both conditions are TRUE.
- || ( OR ) => it returns TRUE, if either of two conditions is TRUE.
- Let's edit out code a little and add a 3rd condition, as shown in below figure:
- Here, I have used three IF Loops in above code and have used && operator in second IF Loop.
- So, if the number is in between 50 & 90, then second loop will execute, both conditions have to be TRUE.
- I hope you have understood How to use IF Loop in C#, now let's move a little forward and have a look at IF Else Loop in C#, which is kind of an extension of IF Loop.
IF-Else Loop in C#
- Instead of using separate IF Loops for different conditions, we can use single IF-Else Loop.
- In our first code, we have used two IF Loops to check whether student has passed or failed.
- Let's rewrite that code using IF-Else Loop, as shown in below figure:
- As you can see in above figure, first I have used IF Loop and placed a condition that if (Marks >= 50) then print "you passed the exam" otherwise simply print "you failed the exam".
- Else condition is like the default option, if "IF" Loop failed to execute then "ELSE" will be executed and if "IF" loop is successful, then "ELSE" will be ignored.
- That was the case for two IF Loops, but what if we have more than two IF Loops, as in our second code, we have 3 IF Loops, let's rewrite that code using IF-Else Loop:
- The above code is working exactly the same as our code with 3 IF Loops but here we are using IF-Else Loop.
- In IF-Else Loop, the first loop will be "if" loop and the last one will be "else" loop while all the intermediary loops will be "else if" loops.
- Here's the final code for today's lecture:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your Physics marks: ");
int Marks = int.Parse(Console.ReadLine());
if (Marks >= 90)
{
Console.WriteLine("You got A+ grade. \n\n");
}
else if (Marks >= 50 && Marks < 90)
{
Console.WriteLine("You passed the exam. \n\n");
}
else
{
Console.WriteLine("You failed the exam. \n\n");
}
}
}
}
So, that was all for today. I hope now you can easily use IF-Else Loop in C#, if you have any problems, ask in comments. In our next tutorial, we will have a look at How to use Switch statement in C#. Till then take care & have fun !!! :)
How to use Arrays in C# ???
Hello friends, I hope you all are having fun. In today's tutorial, we are going to discuss
How to use Arrays in C#. It's our 6th tutorial in C# series and currently we are focusing on basic concepts in C#.
Without understanding these simple concepts, we can't move forward. So, let's get started with Arrays in C#:
How to use Arrays in C# ???
- An array (base type System.Array) is a collection of similar (like-typed) data types, called by a common name. Each data item is referred as an element of array and is assigned an index starting from 0.
- As C# array is an object so we can find its length using member length, which is actually a count of total number of data items in that array.
- Arrays are reference types and implement IEnumerable that's why, we have to use new keyword for new instance of array.
- Here's an example of an array in action:
- You can see in above code that I have first initialized an array named TEPArray and I have fixed its size to 3.
- After that, I have added values in the array at each index 0, 1 and 2. If we count we have 3 positions which is the size of our array.
- After that, I am simply printing those values in the console.
Why we need to use Arrays ???
- Let's say you are working on some project where you need to show marks of some students, let's say 50 students.
- In such cases, it would be too difficult to create separate variable for each student. Instead, you can simply create an array of each subject and save all students' marks in single variable.
- In simple words, we use arrays to handle big data of similar data types.
- Arrays are strongly typed i.e. they take data of single data type, we can't add multiple data types in single array.
- We can't increase Array size after initialization, as in above code I have initialized the array with fixed size of 3 so now if I add a 4th element, then compiler will generate an error. Although, we can use foreach iteration on all arrays in C#, we will discuss that later.
Different ways to initialize Arrays in C#
- There are three different ways to initialize arrays in C#, although they are all same at the end but slightly different in syntax.
- I have shown all these three ways in below figure:
- As you can see in above code, the first way is the same one, we first initialized the array and then added values in it.
- In the second way, we have initialized the array and added values in it, in a single line.
- In the third way, I have just declared the arrays and haven't added the size or the data in it.
- After that I have initialized them and then added values, arrays don't occupy any memory unless initialized.
- Here's the complete code, which we have designed so far:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
// First Way: Initialization first & then added values
int[] TEPArray = new int[3];
TEPArray[0] = 1;
TEPArray[1] = 2;
TEPArray[2] = 3;
// Second Way: Initialization & values added in a single line
int[] TEPArray2 = new int[5] { 1, 2, 3, 4, 5 };
Console.WriteLine("Code Designed by www.TheEngineeringProjects.com \n");
Console.WriteLine("Value at Index 0 is : {0} \n", TEPArray[0]);
Console.WriteLine("Value at index 2 is : {0} \n", TEPArray[2]);
Console.WriteLine("Length of Second Array : {0} \n", TEPArray2.Length);
Console.WriteLine("First element of Second Array : {0} \n", TEPArray2[0]);
// Third Way: Declared First & then initialized & values added
string[] TEPArray3, TEPArray4;
TEPArray3 = new string[5] {"Hello","welcome","to","C#","Tutorial"};
TEPArray4 = new string[] { "Designed", "by", "The", "Engineering", "Projects" };
Console.WriteLine("\n\n");
Console.Write("For loop : ");
for (int i = 0; i < TEPArray3.Length; i++)
Console.Write(TEPArray3[i] + " ");
Console.WriteLine("\n\n");
Console.Write("For-each loop : ");
// using for-each loop
foreach (string i in TEPArray4)
Console.Write(" " + i);
Console.WriteLine("\n\n");
}
}
}
- Till now, we have discussed only One Dimensional Arrays, now let's have a look at Multi-Dimensional Arrays:
Multi-Dimensional Arrays in C#
- We have seen single row of data in arrays so far, but we can also add multiple rows in arrays and such arrays are called Multi-Dimensional Arrays or Rectangular Arrays.
- They are called rectangular because length of each row has to be same in a single array.
- Let's have a look at Multi-Dimensional Array in below figure:
- In the above code, you can see i have created two arrays, the first one TEPArray1 is a 2-Dimensional Array, while TEPArray2 is a 3-Dimensional Array.
- I have also used nested for loop to display data of 2D array, if you can't understand it yet, don't worry we will discuss it in detail in coming lectures.
- But make sure you understand, how I am accessing elements of multi-dimensional arrays.
- Here's the complete code for Multi-Dimensional Arrays in C#:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
string[,] TEPArray1 = new string[4, 2] {
{ "one", "two" },
{ "three", "four" },
{ "five", "six" },
{ "seven", "eight" }
};
int[,,] TEPArray2 = new int[2, 2, 3] {
{
{ 1, 2, 3 },
{ 4, 5, 6 }
},
{
{ 7, 8, 9 },
{ 0, 1, 2 }
}
};
// Accessing array elements.
Console.WriteLine("Code Designed by www.TheEngineeringProjects.com \n");
Console.WriteLine("2DArray[0][0] : " + TEPArray1[0, 0]);
Console.WriteLine("2DArray[0][1] : " + TEPArray1[0, 1]);
Console.WriteLine("2DArray[1][1] : " + TEPArray1[1, 1]);
Console.WriteLine("2DArray[2][0] " + TEPArray1[2, 0]);
Console.WriteLine("\n\n");
Console.WriteLine("3DArray[1][0][1] : " + TEPArray2[1, 0, 1]);
Console.WriteLine("3DArray[1][1][2] : " + TEPArray2[1, 1, 2]);
Console.WriteLine("3DArray[0][1][1] : " + TEPArray2[0, 1, 1]);
Console.WriteLine("3DArray[1][0][2] : " + TEPArray2[1, 0, 2]);
Console.WriteLine("\n\n");
Console.WriteLine("For Loop:");
for (int i = 0; i < 4; i++)
for (int j = 0; j < 2; j++)
Console.Write(TEPArray1[i, j] + " ");
Console.WriteLine("\n\n");
}
}
}
So, that was all about Arrays in C#. If you got into any errors, then ask in comments. In next lecture, we will have a look at How to use Comments in C#. Till then take care & have fun !!! :)
Datatype Conversions in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at Datatype Conversions in C#. We have discussed
C# Data Types in our 3rd tutorial and today we will discuss How to convert one datatype into another.
If you are working on some complex project, then you have to convert one form of data into another i.e. let's say you are getting bill value from barcode reader, this value must be a string and if you want to apply any arithmetic operation on it then you need to convert that string into integer or float. So, let's get started with Datatype Conversions in C#:
Datatype Conversions in C#
- If you are working on some data driven application, then there's always a need to convert one form of data into another and that's where Datatype Conversions are required.
- Few conversions doesn't require any method or class i.e. if we want to convert an integer into float then that can easily be done by the compiler, as there's no chance of data loss.
- Such conversions are called Implicit Conversions, here's an example:
- You can see in above figure that compiler has automatically converted integer into float.
- But if we want to convert a float (let's say 313.56) into integer then we can't do that as integer doesn't have the decimal part.
- So, if we want to convert a float into integer, we will get a compiler error i.e. overflow exception.
- In order to perform such conversions we have to use Explicit Conversions method, pre-defined in C#.
- There are two options for Explicit Conversions:
- Use Cast Operator.
- Use Convert class of C#.
- Both of these methods are shown in below figure:
- Now you can see in above figure that the Cast Operator (int) has just taken the main value and simply ignored the decimal/fractional part.
- While the Convert Class (Convert.ToInt32) has rounded off the number and didn't ignore the decimal part.
String Conversion in C#
- Normally the data received from external/hardware devices, is in the form of strings and we need to convert it into integer or float etc. to perform arithmetic operations.
- There are two options available for String Conversions in c#, which are:
- Here's the implementation of Parse Method for String to integer conversion, in below figure:
- But there's a drawback in Parse that if the string contains alphabetical / special characters then it will create an error and couldn't convert the string into integer.
- So, in order to avoid error, we should use TryParse method, as shown in below figure:
- As you can see in above figure, TryParse takes two parameters:
- First one must be a string, which you want to convert.
- Second one must be an integer, in which the value will be saved.
- Moreover, TryParse method also returns a Boolean type, which will be:
- True, if the conversion is successful.
- False, if the conversion is unsuccessful.
- I have provided a string "323ABC" whcih contains alphabetical characters, that's why ConversionCheck is false and we are not getting any value in our integer.
- Here's a screenshot of one successful conversion of TryParse method:
- Now TryParse is returning True as the conversion is successful and our output integer variable got updated.
- Here's the code used in today's tutorial:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("\n\nwww.TheEngineeringProjects.com\n");
string Num1 = "323";
bool ConversionCheck = int.TryParse(Num1, out int Num2);
Console.WriteLine("\nValue of Num2 : {0}", Num2);
Console.WriteLine("\nValue of ConversionCheck : {0}", ConversionCheck);
if(!ConversionCheck)
{
Console.WriteLine("\nString contains non-numeric Values.");
}
else
{
Console.WriteLine("\nOur Converted int : {0}", Num2);
}
}
}
}
So, that was all about the Datatype Conversions in C#. I hope you have enjoyed today's tutorial. In the next tutorial, we will have a look at
How to use Arrays in C#. Till then take care & have fun !!! :)
Common Operators in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are going to have a look at few Common Operators in C#. It's 4th tutorial in C# series and before going forward, we have to first understand the working operation of these C# operators.
We have a lot of operators in C# but I have discussed few of them, which are most commonly used. If you got into any trouble then ask in comments. So, let's get started with Common Operators in C#:
Common Operators in C#
- Operators are used to create a link, relation or operation between two entities/variables. Few of these C# operators are as follows:
- Assignment Operator ( = )
- Arithmetic Operators ( + , - , * , / , % )
- Comparison Operators ( == , != , > , < , >= , <= )
- Conditional Operators ( && , | | )
- Ternary Operator ( ? : )
- Null Coalescing Operator ( ?? )
- Escape Sequence ( / )
- Verbatim Literal ( @ )
- Let's discuss them one by one in detail:
1. Assignment Operator ( = )
- Assignment Operator is used to assign a value from one entity to another.
- Let's say we initialize an integer with value 5, so what we need to write is int i = 5; so this assignment operator has assigned a value of 5 to integer i.
2. Arithmetic Operators ( + , - , * , / , % )
- Arithmetic Operators ( + , - , * , / , % ) are used for performing different mathematical operations between two entities/variables.
- Each arithmetic operator has its own mathematical operation associated with it. For example:
- ( + ) is used to add two numbers i.e. int a = 5 + 10; so compiler will first apply the arithmetic operator (+) and will add 5 & 10 and after that will use assignment operator to assign the value 15 to variable a.
- ( - ) is used to subtract two numbers i.e. int b = 10 - 5; result will be 5.
- ( * ) is use to multiply two numbers i.e. int c = 10 * 5; result will be 50.
- ( / ) is used to divide two numbers i.e. int d = 10 / 2; result will be 5.
- ( % ) is used to get the remainder of two numbers i.e. int e = 22 % 4; result will be 2.
3. Comparison Operators ( == , != , > , < , >= , <= )
- Comparison Operators ( == , != , > , < , >= , <= ) are used to compare two entities with one another.
- We will discuss them in detail in Loops section while discussing if loop.
- a == b, it will check whether a is equal to b.
- a != b, a is not equal to b.
- a > b, a is greater than b.
- a < b, a is less than b.
- a >= b, a is greater than or equal to b.
- a <= b, a is less than or equal to b.
- I am using few Comparison operators in this right figure.
4. Conditional Operators ( && , | | )
- Conditional Operators ( && , | | ) are used to create a relation between two conditions.
- This one will also be discussed in more detail in IF Loops section.
- && , It is pronounced as AND, this operator makes sure that both conditions must be true.
- | | , It is pronounced as OR, this operator returns TRUE if either of the two conditions is true.
- I have placed a conditional operator in right figure, I have placed a check that value must be greater than 10 and less than 20.
5. Ternary Operator ( ? : )
- Ternary operator is one of the coolest feature of C# and comes quite handy at times.
- It's a simple form of if loop, which reduces the IF Else Loop code in single line. We will discuss it in C# IF Loop lecture.
6. Null Coalescing Operator ( ?? )
- Null Coalescing Operator ( ?? ) is used to convert nullable value into non-nullable value.
- Let's say we have two integers a and b defined as:
int? a = 15; (nullable variable)
int b = 0; (non-nullable variable)
- Now we want to save value of a into b so if you write a = b; compiler will generate an error.
- So, in order to do that you need to use Null Coalescing Operator ( ?? ) as follow:
int b = a ?? 0;
- if the value of a is null, then b will become 0. It's called the default value, you can set it to anything, I've made it 0.
Complete Code
- Here's the complete code used in this tutorial:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Numer 1: ");
int Num1 = int.Parse(Console.ReadLine());
Console.Write("Enter Numer 2: ");
int Num2 = int.Parse(Console.ReadLine());
int Total = Num1 + Num2;
if (Total > 10 && Total < 25)
{
Console.WriteLine("Total count is {0}", Total);
}
else
{
Console.WriteLine("Total count is less than 10 or greater than 25");
}
}
}
}
I hope you have learnt something from today's tutorial. Let me know if you have any questions in comments. Take care & have fun !!! :)
NuGet Package Management in ASP.NET MVC
Hello friends, I hope you all are doing great and having fun with your lives. In today's tutorial, we will discuss in detail about NuGet Package Management in ASP.NET MVC. It's 15th tutorial in ASP.NET MVC series. Today's tutorial is not about programming, instead we are gonna discuss this pre installed tool NuGet Package Management in ASP.NET MVC.
NuGet Package Management is use to install packages and libraries, which you want to use in your project. It downloads the files online and then installs it. So, let's discuss this ASP.NET MVC tool in detail:
NuGet Package Management in ASP.NET MVC
- NuGet Package Management is a package manager for ASP.NET MVC, which is used for downloading and installing different packages & Libraries online.
- If any of your packages needs to be updated, then it can also be done by NuGet Package Management.
- There are many third part packages available online, even there are many independent packages developed by Microsoft itself, which you can easily download & install using NuGet Package.
- These third party packages could be open source or closed source.
- So, now let's have a look at How to install any package using NuGet Package Management in ASP.NET MVC.
- Right Click on your Projects' name in Solution Explorer and then click on Manage NuGet Packages, as shown in below figure:
- It will open up a NuGet window in your workspace, as shown in below figure:
- You can see in above figure that NuGet window is opened and it has three tabs:
- Browse: For browsing new packages.
- Installed: Search pre-installed packages in your visual studio.
- Updates: Here you will get the notifications for updates of your pre-installed packages.
- On the right side of each package, we have two versions listed.
- The upper version is the installed version of that package in your visual studio software and the lower one is currently available version.
- You can click on the upper arrow to update that package.
- Here's the video demonstration of NuGet Package Management in ASP.NET MVC:
So, that was all about NuGet Package Management in ASP.NET MVC. It was a quick tutorial as I don't have much to explain here, its a simple tool but you should know about it as it will be used in coming tutorial. That's why I have posted it. If you have any questions, please ask in comments and I will try my best to help you out. Thanks for reading, have a good day. Take care !!! :)
Validation in ASP.NET MVC
Hello friends, I hope you all are doing great. In today's tutorial, we will discuss
Validation in ASP.NET MVC. It's our 14th tutorial in ASP.NET MVC series. In our previous tutorial, we have seen
Model Binding in ASP.NET MVC and you have seen we have created a View for our Model class.
In today's tutorial, we are gonna add some validations on the data provided by the users in those Text box fields. We will place some constraints like the age must be above 13 or the characters of name must be between 4 to 20. So, let's have a look at How to deal with Validation in ASP.NET MVC:
Validation in ASP.NET MVC
- Validation uses built-in attribute of ASP.NET called DataAnnotations and is used to validate inputs provided by the user.
- Validation is a very powerful attribute of ASP.NET MVC and it can be applied to entire model class or any property of model class.
- It places a restriction on the inputted data by the user, and if the data doesn't follow the specified rules then it will generate an Error Message and won't allow the user to submit form.
- It's really helpful from development point of view, as the developer always gets the data in single specified format, thus can easily handle it.
- Following table shows few of the most commonly used Validations in ASP.NET MVC:
Validation in ASP.NET MVC |
No. |
Attribute |
Description |
1 |
Range |
Value sould lie b/w specified range (e.g. Age) |
2 |
StringLength |
Maximum Characters (e.g. First Name) |
3 |
Required |
This field is Compulsory. (*required) |
4 |
RegularExpression |
The user input must match the provided format (e.g. Date / Time) |
5 |
MaxLength |
Sets the Maximum Limit. |
6 |
CreditCard |
For Credit Card details. |
7 |
CustomValidation |
Custom validations defined by developer. |
8 |
FileExtension |
Restriction on File Extension (e.g. only img file) |
9 |
MinLength |
Sets the Minimum Limit. |
10 |
EmailAddress |
Email Address must be provided. |
11 |
Phone |
Phone Number Format must followed. |
- I hope you have now got the basic idea of what is validation.
- Now let's implement one of these validations in ASP.NET MVC.
- So, open your StudentModel.cs file, it's our model class which we have created in tutorial: How to Create a New Model in ASP.NET MVC.
- You can see in the above figure that I have added an attribute before Name variable.
- It's a StringLength Validation and the first parameter which I have set to 20 is the maximum length of string allowed.
- While minimum length is specified as 4, so this Validation is restricting the Name model to only accept value of length between 4 and 20.
- So, now run your application and check the View and in Name Text box enter your name, here are the results:
- In Case 1, the input string length is less than 4, while in Case 2, length is greater than 20.
- That's why it has given error in both cases.
- We can also add multiple Validation to single property, as shown in below figure:
- Below this StringLength, I have placed another Validation in ASP.NET MVC which is [Required].
- So, now it will also make sure that Name field is not empty.
- Here's the video demonstration of Validation in ASP.NET MVC, have a look at it:
So, that was all about Validation in ASP.NET MVC. I hope you have enjoyed today's tutorial and I would suggest you to try all those Validation as a homework and share your codes with us in the comments. Thanks for reading, Take care !!!
Model Binding in ASP.NET MVC
Hello friends,I hope you all are doing great and having fun with your lives. In today's tutorial, we are gonna have a look at
Model Binding in ASP.NET MVC. It's our 13th tutorial in ASP.NET MVC series. Today, we are gonna discuss a new concept in ASP.NET MVC and it's more of a luxury as it automates the job and makes our work easy.
Suppose, in your application, you want to create a registration form and thus you need to pass this data from View to your model, so that it could be saved in your database. So, in order to bind this HTTP request data from View to Model, we use Model Binding. Let's have a look at Model Binding in ASP.NET MVC in detail:
Model Binding in ASP.NET MVC
- Model Binding in ASP.NET MVC is used to bind the data sent by the HTTP request with Model.
- You must have viewed during some form submission online, that when you click on the submit button then a form of data is sent by the HTTP string.
- This HTTP data is linked to the Controller's action methods in the form of input parameters.
- For example, suppose we have an action method "public ActionResult Edit(int id)", here the parameter int id could be used as a model binder.
- It may happen that this id value is coming from some HTTP request "http://localhost/Student/Create?id=10".
- So, the model binders get data from View via HTTP request and then pass this value to Controller's action method, which in turn shows up to models.
- When we create a new form in ASP.NET MVC, then this model binding is automatically done by visual studio.
- Let's create a new View and have a look at working of Model Binding in ASP.NET MVC.
- So, in your StudentController.cs file, right click on the action method Create and then click on Add View, as shown in below figure:
- When you click on the Add View, it will open a New Window for Creating a View.
- We have already seen it in How to Create a New View in ASP.NET MVC.
- So, here's the screenshot for the settings, first I have given this View a name Create, then I have selected Create Template.
- Finally, I have selected the Model class, which we have created in one of our previous tutorial: Create a New Model in ASP.NET MVC.
- After these settings, click the Add Button and a new View for the Create action method will be created.
- Create.cshtml file will open up in your workspace, as shown in below figure:
- If you remember the Student Model, it has four variables as shown in below figure:
- So, let's open our newly created Model in the browser.
- If everything goes fine then you will get similar results:
- You can see in the above figure that visual studio has created the same four fields in the View which were present in the Model class.
- The data we will enter here will be sent to the model and then will be saved in the database.
- Code for the Model Binding in ASP.ENT MVC has automatically been created, which we have seen in Create.cshtml.
- Here's the video demonstration of Model Binding in ASP.NET MVC:
So, that was all about Model Binding in ASP.NET MVC. If you got into any trouble in understanding it, then ask in comments. In the next tuorial, we will have a look at Data Validation in ASP.NET MVC. Thanks for reading, Take Care !!! :)
HTML Helpers in ASP.NET MVC
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at
HTML Helpers in ASP.NET MVC. It's our 12th tutorial in ASP.NET MVC series. I know every tutorial is a new concept for you to understand but we have to cover all of them before starting working on our project in ASP.NET MVC.
If you have worked on ASP.NET web forms or C# / Visual Basic projects then you must be aware of toolboxes, from where we can drag and drop our visual components like textbox, editbox, button etc. But in ASP.NET MVC applications, we don't have this luxury of drag and drop. Instead we have HTML Helper classes which are used to created these html components in ASP.NET MVC. So, let's have a look at How to use HTML Helpers in ASP.NET MVC:
HTML Helpers in ASP.NET MVC
- HTML Helpers are simple C# classes in ASP.NET MVC, which are used to create HTML components in the run time environment.
- HTML Helper creates a path for displaying model values (saved in SQL Databases) in respective HTML components e.g displaying name in Name Text Box.
- We can also get values from HTML components and then save them in our database via Model. You should recall Tut # 02: What is a Model ?.
- So, instead of drag and drop as in C# applications, in ASP.NET MVC we are generating and controlling our HTML components programmatically using HTML Helper classes.
- There are numerous HTML Helpers are available in ASP.NET MVC but the most commonly used HTML Helpers are shown in below table:
HTML Helpers in ASP.NET MVC |
Type |
Forced Type |
Description |
Html.TextBox |
Html.TextBoxFor |
It creates a Text Box. |
Html.TextArea |
Html.TextAreaFor |
It creates a Text Area. |
Html.CheckBox |
Html.CheckBoxFor |
It creates a Check Box. |
Html.RadioButton |
Html.RadioButtonFor |
Radio buttons are created using this HTML Helper. |
Html.DropDownList |
Html.DropDownListFor |
Drop Down List is created with it. |
Html.ListBox |
Html.ListBoxFor |
It is used to create Multi-select list box. |
Html.Hidden |
Html.HiddenFor |
Hidden fields are created with it. |
Password |
Html.PasswordFor |
Password text box are created with it. |
Html.Display |
Html.DisplayFor |
It creates Html text. |
Html.Label |
Html.LabelFor |
Labels are created here. |
Html.Editor |
Html.EditorFor |
Editor is created using it. |
Html.ActionLink |
|
It creates Anchor link. |
- In normal HTML language, we use html tags e.g. <a> this html tag is used for linking, but in ASP.NET MVC we use HTML Helper and HTML Helper makes it too easy to bind model data with View design.
- For example, if we are working on simple html then we will use
<a href="/Student/Click ME">Click ME</a>
this code to create a link, but in HTML Helper it will be @Html.ActionLink("Click ME", "Click ME")
.
- I have simply used Action Link, which will create a Link component and then I have given it a name and then action method.
- So, when you click on it then Click ME action method will be called.
- Open the index.cshtml file of our Student Controller. ( Recall: Tut # 6: Create a New Controller in ASP.NET MVC )
- I have removed the extra code in this index file and have added a new HTML Link Helper, as shown in below figure:
- You can see in above figure that Link Helper has two inputs, the first one is the Anchor Text of the Link, while the second one is the action method which should be called i.e. Get1().
- Here's the video demonstration of HTML Helpers in ASP.NET MVC:
So, that was all about HTML Helpers. You must have got the idea that Html Helpers are not that difficult, in fact they are here to ease the job. Thanks for reading. Take care & have fun !!! :)