In Technologies
0
2391

ASP.NET MVC is an open-source web development framework and this framework implements the MVC patterns which help to provide separation of code. It is the standard software design pattern that separates an application into three main components. i.e. Model, View, Controller for developing the web application.

MVC Components

Following are the components of MVC:

Every layer in MVC is assigned a unique responsibility.

Model:-  Model represents a set of classes that represent data and uses validation logic to enforce business rules or how the data can be changed and manipulated and the application that handles the logic or the application data. Often model object retrieves and stores model state in the database.

View:- It is responsible for the overall look and feel for transforming the models into User-interface and basically view is responsible for displaying all portion of the data to the end user.

Controller:- Actually Controller is the heart of the MVC Architecture. The responsibility of the controller is to control the application logic and acts as the mediator between view and model.

Create an MVC 4 Web application with an empty solution with the project name SimpleBlog.

  Create MVC4 Application

Select Empty Template

Our Basic setup is ready. The solution will look like below after adding the necessary projects.

Solution Explorer

Let’s create a controller by right-clicking at the Controllers folder -> Add -> Controller. Name the controller as HomeController.

Add Controller

Add Home Controller

HomeController.cs

using System.Web;

using System.Web.Mvc;

namespace HelloWorld.Controllers

{

public class HomeController : Controller

{

public ActionResult Index()

{

return view();

}

}

}

Index.cshtml

@{

 Layout = null;

 }

 <!DOCTYPE html>

 <html>

 <head>

 <meta name="viewport" content="width=device-width" />

 <title>index</title>

 </head>

 <body>

 welcome to my first MVC Page
 </body>

 </html>

Explaining MVC routing

Routing simplifies your MVC URL like Home/Home/GotoHome —> /Home

It is nothing but it is a collection which maps the user-friendly URLs with the controller names and method names. Map-route is a method and contains the three important things i.e. name, URLs and default.

routes.MapRoute(

name: "Default",                   //Route name

Url: "{controller}" /{action} /{id}",       //Url Pattern

defaults: new { controller = "Home", action = "Index", id= UrlParameter }    //Default for Route

);

For Example:- Configure Route In MVC

public class RouteConfig

{

public static void RegisterRoute(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{"pathInfo}");

routes.MapRoute(

name: "Default",

Url: "{controller}" /{action} /{id}",
defaults: new { controller = "Home", action = "Index", id= UrlParameter.optional }

);

}

}

Routing in MVC:-

http://localhost:123/Home/Index/1000              //urls Pattern

Here: Home is the controller, Index is the Action method and ID is the parameter value(optional).

What are the different mechanisms of passing data from Controller to View in an Asp.neMVC?

In asp.net the various ways to passing data in around your web application using ViewState, Hidden fields and session variables etc.

Important Point:-

1. There is No View State in Asp.net MVC.

2. There is No Behind Code in MVC.

3. And last there is No Server controls in MVC architecture.

So, there are no view state how to pass data around MVC.

There are four primary mechanisms by which we can pass data in an Asp.net MVC architecture:

ViewData

ViewData is used to pass data from controller to the corresponding view or action to the view then you will use ViewData. It required typecasting for getting data.

Example:-

HomeController.cs

using System.Web;
using System.Web.Mvc;
namespace HelloWorld.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData[MyTime]=DateTime.Now.ToString();
return view();

}
}
}

Index.cshtml

@{

 Layout = null;

 }

<!DOCTYPE html>

<html>

 <head>

 <meta name="viewport" content="width=device-width" />

 <title>index</title>

 </head>

 <body>

@ViewData["MyTime"]

 </body>

</html>

 ViewBag

It’s also used to pass data from controller to the corresponding view and it does not require to typecasting for getting data and it is a dynamic property that takes and makes its syntax easy.

//   ViewData["MyTime"] = DateTime.Now.ToString();

ViewBag.MyTime = DateTime.Now.ToString();        // Homecontroller.cs

//  @ViewData["MyTime"]

@ViewBag.MyTime                 // Index.cshtml

Note:- ViewData or ViewBag does not maintain data from controller to controller or Action to Action and it only maintains data from controller to the View.

Tempdata

It is used to pass data from controller to controller or Action to Action then from action to a view for a single request then you will use temp data. It is also used for typecasting for getting data.

Examples:- Using TempData to get data after redirect as well.

public class HomeController : Controller

{

public ActionResult Index()

{

TempData["MyTemp"]= DateTime.Now.ToString();

ViewBag.MyTime=DateTime.Now.ToString();

return redirectToAction("GotoHome" , "Home");
}

public ActionResult GotoHome()

{

return view();

}

}

Index.cshtml

@{
 Layout = null;
 }

<!DOCTYPE html>

<html>

 <head>

 <meta name="viewport" content="width=device-width" />

 <title>index</title>

 </head>

 <body>

@TempData["MyTemp"]

@ViewBag.MyTime

 </body>

</html>

TempData helps to maintain throughout the single request but that was only the partial truth. In this blog we are going to elaborate that thing much more and will try for more details. Lets me go for full truth here

TempData can also preserve values for the next request depending on four conditions:-

  1. Not read:- “TempData” will be persisted for the next request, if you do not read the value.
  2. Read:- “TempData” will not persist for the next request, if you read the value.
  3. Read and Keep:- If you read the “TempData” and call the “keep” method it will be persisted for next request.
  4. Peek and Read:- If you read “TempData” by using the “Peek” method it will persist for next request.

Session variables

The session is used for maintaining data between multiple requests and until browser or session is open then we have to use session variables. Like TempData the value must be type-casted when it is used for processing.

session["MySession"]= DateTime.Now.ToString();

Note:- Session will survive until you close the browser for again send the second request. It maintains data for a complete session until the browser is open.

Why have they given so many ways for passing data around MVC?

Because of the data is used and the memory is occupied till what is needed for example when you pass the data from the controller to the view after that you don’t need the data then view bag and view data will go for garbage collection by it shows or put less stress on your memory or server memory. Temp data for one single request complete then go for garbage collection and scope is finished the garbage collection runs in the background for releasing your ram.

We have only explained the basic of MVC in this part and I hope you enjoyed reading it and was easily able to learn it step by step.

RECOMMENDED POSTS

Start typing and press Enter to search