Wednesday, 20 May 2015

ViewData and ViewBag in Asp.Net mvc

In MVC  there are 3 way to pass the data from controller to view
1.   ViewData,
2.   ViewBag,
3.   TempData ,
We can also use session for passing the data from controller to view , every property has its own importance.

ViewData:-  
1.   Basically ViewData is a directory which is derived from  the ViewDataDictonary class.
public ViewDataDictionary ViewData { get; set; }

2.    it  is a property of  “ControllerBase” class.
3.   It is used to passing the data from Controller to respected view.
4.   Its life lies for the current request.
5.   Its need typecasting for getting the data because it can’t handle null so for checking the null value for avoiding error.
6.   It is similar to Application state or Session state for passing the data.
//Controller code

public ActionResult Index()
{
      List<string> Courses = new List<string>();
     Courses.Add("COMPUTER SCIENCE");
     Courses.Add("DOT NET");
     Courses.Add("C++");
     Courses.Add("INFORMATION TECHNOLOGY");

      ViewData[“Courses"] = Courses;
      return View();
}
//View code
<ul>
    <% foreach (var Courses in ViewData["Courses"as List<string>)
        { %>
    <li><%: Courses %></li>
    <% } %>
</ul>


Or we can write it with different way also
//Controller code
public ActionResult Index()
        {
            ViewData["Courses"] = new List<string>()
    {
        "COMPUTER SCIENCE",
        "DOT NET",
        "C++",
        "INFORMATION TECHNOLOGY"
    };
            return View();
        }


//View Code

@{
    ViewBag.Title = "Courses Name";
}

<h2>Courses Name</h2>
<ul>

@foreach (string Courses in (List<string>)ViewData["Courses"])
{
    <li>@Courses</li>
}

</ul>


This view needs a type casting.

View Bag :-
1.   viewBag is a dynamic property which is introduced in C# 4.0.
2.   It  is also used to pass the data from the controller to view.
public Object ViewBag { get; }

3.   It   is the property of controller base class.
4.   Its also life lies for only for current request.
5.   There is no need for typecasting.

public ActionResult Index()
{
           List<string> Courses = new List<string>();
     Courses.Add("COMPUTER SCIENCE");
     Courses.Add("DOT NET");
     Courses.Add("C++");
     Courses.Add("INFORMATION TECHNOLOGY");

      ViewBag.Courses = Courses;
      return View();
//page code
<ul>
    <% foreach (var Courses in ViewBag.Courses)
        { %>
    <li><%: Courses%></li>
    <% } %>
</ul>

   //Controller code

    public ActionResult Index()
        {
            ViewBag.Courses = new List<string>()
    {
        "COMPUTER SCIENCE",
        "DOT NET",
        "C++",
        "INFORMATION TECHNOLOGY"
    };
            return View();
        }

//View Code
@{
    ViewBag.Title = "Courses Name";
}

<h2>Courses Name</h2>
<ul>

@foreach (string Courses in ViewBag.Courses)
{
    <li>@Courses</li>
}

</ul>

TempData : -

1.   TempData  is a Directory which is derived from the TempDataDictionary.
public TempDataDictionary TempData { get; set; }

2.   It   is the property of controller base class.
3.   It is used to pass the data from controller to view.
4.   Its life is very short means its lies till the respected view fully loaded.
5.   There is need for typecasting.
6.   It is used to store one time message ex. Validation message or error message.
//Controller Code
public ActionResult Index()
{


           List<string> Courses = new List<string>();
     Courses.Add("COMPUTER SCIENCE");
     Courses.Add("DOT NET");
     Courses.Add("C++");
     Courses.Add("INFORMATION TECHNOLOGY");

    TempData["Courses"] = Courses;
    return View();
}
//page code
<ul>
    <% foreach (var Courses in TempData["Courses"as List<string>)
        { %>
    <li><%: Courses %></li>
    <% } %>
</ul>


Session
1.    Session is a property of Controller base class which type is HttpSessionStateBase.
public HttpSessionStateBase Session { get; }


2.   it is also used to pass data Unlike TempData, it persists for its expiration time (by default session expiration time is 20 minutes but it can be increased).
3.   it is valid for all requests, not for a single redirect.
4.   It’s also need typecasting for getting data and for  checking null values to avoid error.


View in Asp.net MVC

Here we will discuss View in MVC with an example , As we discuss before that View in MVC is used to show the data to user.
Step(1) :- Go to your application and right click on Controller and add a new controller and give name it as “HomeController” and give Scaffolding option as Empty MVC Controller, And click ADD.
After Click add there is Default Function name is “index” with return type is “ Action result” will be available.

Step(2) :- Now here we want to display list of courses available in IT filed. So for that we have to change the return type of this Index Method As List of String because Courses will be in String format. So let’s change the return type of this method.
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public List<string> Index()
        {
            return new List<string>()
    {
        "COMPUTER SCIENCE",
        "DOT NET",
        "C++",
        "INFORMATION TECHNOLOGY"
    };
        }

    }
}


We can assess these courses name from database but here we are doing as hardcoded.
  Step(3):-  At  this point if we run our application we will see output as not expected means it will not shoe the name of courses “System.Collections.Generic.List`1[System.String]”  for showing the output as we want we have to add the view to our application
The purpose of view to render the data or format of data as end user wants , in view we can change the format of data means if we want data as bold , colour we can do. So the work of view is to present the data to the end user .
Step(4): Now add a view for this method , so right click on index function add a view

After click on Add view you will see a view window there you will see that the view name is same as Controller name and View engine as Razor Engine after click on ADD. Then you will see a View in View Folder of your application.

If we see that where this Index View add then go to solution explore in View folder there is another folder as HOME and then you will your Index View. Actually here why is view is under home folder because this View is for Home Controller method  , So all the view which are related to this home controller will come under this home Folder.
Step(5):- Now we have to change the return type of this index method which exists in Home controller for showing result in home controller. Now return type will be “Action result”
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return new List<string>()
    {
        "COMPUTER SCIENCE",
        "DOT NET",
        "C++",
        "INFORMATION TECHNOLOGY"
    };
            return View();
        }

    }
}



Here it return a view but how it will find a Index View for that while executing application it will go to View folder and there it will see Home Folder (because Controller name is home) then it will find a View name as Index(Because controller method name is Index).
Step(6): Now here we want list of Courses for showing list of courses here need to pass Courses list from Controller to View . There are several method for passing data from controller to view.
We can use ViewData, View Bag or View modal. Here for passing the data from Controoler to view we will use ViewBag, Means we have to store this information to a property so here we will store this courses information into ViewBag.Courses(Here Courses is any meaningful name) .
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Courses = new List<string>()
    {
        "COMPUTER SCIENCE",
        "DOT NET",
        "C++",
        "INFORMATION TECHNOLOGY"
    };
            return View();
        }

    }
}


Step(7) :- So now for showing list of Coruses we have to change in Index.csHtml class go to Index.csHtml class and give the title name.
For showing the data in list we have to make the foreach loop using the HTML helper  for getting this HTML Helper control start with “@” symbol.
This  "@" symbol is used to switch b/w  html and c# code
@{
    ViewBag.Title = "Courses Name";
}

<h2>Courses Name</h2>
<ul>

@foreach (string Courses in ViewBag.Courses)
{
    <li>@Courses</li>
}

</ul>


Now Run your application and you will see the courses name as List.

Here if we see the return type of view is ViewResult but we wrote index method with ActionResult return type that because if you will go to definition of this view you will see that this ViewResult is inherited from the ActionResult.

Note:- For Passing the data from Controller to View , we should use Strongly type View modal instead of using ViewData And ViewBag.

Difference Between ViewResult and ActionResult in MVC.

Here we will understand difference between View Result and Action result.  Basically Action result is an abstract class which has subtypes and the View result class is derived from Action Result class.
“View Result” is derived from Action Result , so Action Result in MVC is an abstract parent class



See the below code
public ActionResult Index()
{
      return View(); 
}


In the above code we can see that it is returning a “View Result” object and cause of polymorphism this “View Result” object automatically types casted for the parent class means “Action result”.
 Action Result Subtypes:-
  • ViewResult - Renders a specified view to the response stream
  • PartialViewResult - Renders a particular partial view to the response stream
  • EmptyResult - An empty response is given.
  • RedirectResult - It Performs an HTTP redirect to a specified URL
  • RedirectToRouteResult - Performs an HTTP redirection to a URL that is decide by the routing engine, based on given data from route.
  • JsonResult - Serializes a given View Data object to JSON format
  • JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  • ContentResult - its Write content to response stream without need of a view
  • FileContentResult - Returns a file to the client
  • FileStreamResult - it Returns a file to the user, that is provided through a  Stream
  • FilePathResult - it Returns a file to the user




C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...