Wednesday 30 December 2020

ViewData ViewBag and TempData

In this article I will show you how to pass/exchange data in MVC. ViewData and Viewbag are simple properties and I'm not going to concentrate more on it but TempData. TempData provide more control while passing data.

    1.       ViewData

    2.       ViewBag

    3.       TempData

 

Let’s create MVC5 application with name ViewDataViewBagTempData.

 

ViewData : ViewData is dictionary object used to pass data from controller to view. It is introduced with MVC 3 version.

Create Method1 action method in Home controller.



Right click on Method1, select Add View option and click on Add button.


View gets added in Home folder under Views. Add ViewData[“Movie Name”]


Run application using F5(function key + 5).

ViewBag: It dynamic object used to pass data from controller to view. It is introduced in MVC4 and its like wrapper on ViewData object.

 

Add action method in home controller with ViewBag shown below in highlighted and create view for method2.


Add ViewBag in view and run application.



Movie name (3 Ediots) showing on browser for Home/method2.



TempData: Tempdata is little different from ViewBag and ViewData. Tempdata is used to pass data from controller to view, view to controller and from one controller to another controller.

 

Add action method method3 in Home controller and add view for method3.


 

Update below razor code in method3.cshtml file created for method3 action method.


Create action method with name method4 and add view for this method.


Now run application and type controllername=Home and action = method3 in URL highlighted.


Now click on Navigate to Method 4 action highlighted above and put breakpoint on method4 action method before clicking on above highlighted link from above view. To Open quick watch window select 'TempData.ContainsKey("MovieName")' and press Shift + F9.

Somehow TempData not working as expected. From action method3 TempData pass MovieName to view but not from view to action method method4. To make TempData to work add below code in action method3. TempData.Keep() is used to hold key for subsequent request.


Now run application again and type controller = Home and action= method3


And click on highlighted link above.


Now we found key and it will enter inside if block. In above example we pass movie name from controller to view and again from view to controller with the help of TempData.

Let’s pass TempData from one controller action method to another controller action method and then view. Update action method3 code shown below.


Create new controller with name Default and Index action inside Default controller with below code.


Create Index view for above Index action method in default controller and update index view with below razor code.



Run application with Home/method3 and put breakpoint in action method3 and Index action of default controller.

Press f5 function key or debug it line by line using f10 function key. Control redirect to Index action of default controller shown below.




TempData key found inside Index action method and also Index view using same Tempdata to show movie name.


We discussed all ViewBag,ViewData and Tempdata all three not showing compilation error if misspell property.

ViewData[“Movie Name”]  - >  actual property and on view if you write ViewData[“MovieName”], it won’t give any compilation error but you notice this issue at runtime when you actually execute application and view gets loaded empty or error if you’re dealing with any complex data inside ViewData. Same applicable for ViewBag and Tempdata.






Tuesday 29 December 2020

If-Else statements

                                                                                                                               #15 minutes of reading


In this article, I show you decision making in c#. C# program making decision based on logical condition provided.

Before going into code lets understand this with an example. Suppose you want to go from location1 to location 2. To find the route you search the location in google map and Google map shows you shortest route to reach destination. How google map found shorted route from 3 or 4 routes? It means in background Google map checks distance in kilometer and shows you shortest route. Here distance in kilometer is condition (logical condition) to find shortest route.

We will do same example in C# for finding shortest route.

Source location: Pune

Destination Location: Delhi

Two routes found

1.       Route 1: 1441km (shorted route)

2.       Route 2: 1470km

Let’s understand this with example. Create console application using visual studio 2019 community version.


C# support operator in logical condition like above > (greater than operator) used. Below are few examples of operator C# support in logical condition.

Operator

Description

Greater than

Less than

==

Equality operator

!

Not

!=

Not equal

  

If else condition:

if (condition)

{

    execute code inside green color braces if condition becomes true

}

else

{

    execute code inside red color braces if condition becomes false

}

 

Nested if else:  

if (condition)

{

    //execute code inside green braces if condition becomes true

        if (condition)

    {

  //execute code inside orange color braces if condition becomes true

    if (condition)

  {

     //execute code inside pink color braces if condition becomes true

  }

    }

}

else

{

    execute code inside red color braces if all condition fails

}

 

If else ladder:

if (condition1)

{

    execute code inside green color braces if condition1 becomes true

}

Else if(condition2)

{

    execute code inside orange color braces if condition2 becomes true

}

Else if(condition3)

{

    execute code inside red color braces if condition3 becomes true

}

 


Below program implemented all if-else scenarios discussed above.

static void Main(string[] args)

        {

            Console.WriteLine("Please select Below country to check list of state in country by writing Below                                name");

            Console.WriteLine("1. India");

            Console.WriteLine("2. USA");

            string counrty = Console.ReadLine();

 

            if(counrty.ToUpper() == "INDIA")

            {

                Console.WriteLine("Please select Below State to check list of city in country by writing Below                                 name");

                Console.WriteLine("1. Maharashtra");

                Console.WriteLine("2. Telangana");

                string state = Console.ReadLine();

                Console.WriteLine("List of cities in " + state);

                if (state.ToUpper() == "MAHARASHTRA")

                {                   

                    Console.WriteLine("1. Mumbai");

                    Console.WriteLine("2. Pune");

                    Console.WriteLine("3. Nagpur");

                }

                if (state.ToUpper() == "TELANGANA")

                {

                    Console.WriteLine("1. Hyderabad");

                    Console.WriteLine("2. Nalgonda");

                    Console.WriteLine("3. Nizamabad");

                }

            }

            else if(counrty.ToUpper() == "USA")

            {

                Console.WriteLine("Please select Below State to check list of city in country by writing Below                                 name");

                Console.WriteLine("1. California");

                Console.WriteLine("2. Texas");

                string state = Console.ReadLine();

                Console.WriteLine("List of cities in " + state);

                if (state.ToUpper() == "CALIFORNIA")

                {

                    Console.WriteLine("1. Los Angeles");

                    Console.WriteLine("2. San Jose");

                    Console.WriteLine("3. Oakland");

                }

                if (state.ToUpper() == "TEXAS")

                {

                    Console.WriteLine("1. Austin");

                    Console.WriteLine("2. Houston");

                    Console.WriteLine("3. Dallas");

                }

            }

            Console.ReadLine();

        }

 

 

 

Executing above program will show you below output in console.



Type India/USA and press enter to see list of states.

Now type Maharashtra/Telangana and press enter to see list of cities.


 

Same program shows different list when you select country as USA. Program decides output based on input condition and show results to end user.

 

 

 

 

 

 

Sunday 27 December 2020

Keywords and Variables

                                                                                                                                  #5 minutes of reading

 

In this article I will explain keywords and variables in C#. Every language has keywords and variables.

Keyword is unique words and it has some special meaning. These unique/reserved words called as keywords. Below are few keywords from C#.  for example, public is keyword which tells compiler it is specified and used for declaring scope of method or class. Will discuss lots of keywords in coming article.   

class, const, new, static, void, …etc. are examples of keywords

 

Variables are used to hold value which C# program needs for further processing. We can say variable is container to hold data for C# program.

Let’s create addition and subtraction C# program without variable. You can see drawback of program without variable its hardcoded and every time Calculation function print same result. How can we make it generic? the answer is using variable

 

Below program with variable. Now I can pass number in calculation method and its not hardcoded now we have different result compared to previous screen. Highlighted int a and int b is variable.


Variable is container which hold value and variable can be used in several places in C# program.

 C# variables are categorized into two types:

      1.       Value Type

      2.       Reference Type

 

Value Type:

Data (5) stored directly in stack memory along with variable address(num1) is called as value type. Let’s understand this with example


 

Int, float, double, char, bool, …etc. are examples of value type. Value type derived from namespace System.ValueType. Don’t worry if you don’t understand what namespace is, will cover in coming future article.


I have created small program and covered few most common types and range of type in above screen. If number exceed 2,147,483,648 in that case integer won’t support as limit of integer is 2,147,483,647, we need to switch to float type. If number crossed limit of float, then switch to double.  Types have range start and end choose appropriate type for your program.

  

Reference Type:

Data (John) is not stored along with name of variable (name) in stack memory but the address of heap memory stored in stack along with variable name(address). String, array and class is example of reference type.



As of now understand the concept of value type and reference type later will cover all common types from Value and reference types.

C# Hello World Application

                                                                                               #10 minutes of reading with hands on

 

In this article I will show you what is console application and basics of console application. Console application is light weight program which operates on command prompt. We as programmer needs to provide proper information/message (console messages) so that end user can read and perform operation from command prompt.

Let’s understand with an example. I’m using Visual Studio 2019 community version and console application project from .NET Core framework. There not much difference in .NET Core framework console application and .NET framework console application.

Open visual Studio and click on highlighted create a new project shown in below screen.


It will open below screen. Now select C# as language, operating system as Windows and application type as Console highlighted below. It shows console application from both framework (Core and normal). In this article I’m creating project from Core framework and click Next button.


Set project name HelloWorldProgram


Console application gets created with default class Program and method (Main) inside it.

 

Run console application by using F5 key or in above screen green triangle highlighted, click on it. If you’re using console application from normal .NET framework and not from Core, you need modify main method little bit to hold console screen. 


 

The program executed and print Hello World on command prompt.


Update Main method to read input from console (your name) and print. Console.WriteLine is used to print message on console and Console.ReadLine is used to read input from console.


Same piece of code without Nextline. If you notice in below screen Line is missing in Console.Write and you need to write your name after message ‘Please Enter your Name’. If you enter program execute without reading name.

 

Console.Write: write message on console

Console.WriteLine: write message on console and perform enter key so next message will be printed on new line.

Console.ReadLine(): Read input from console.