ASP.NET MVC

ASP.NET MVC

ASP.NET

ASP.NET is a Microsoft web application framework build on common language run time for building dynamic websites using one of the programming languages like C#, VB.NET etc..

WHAT IS ASP.NET web form?

Microsoft first bought out Asp.net web forms from asp which solved lots of problems by creating higher level abstraction over stateless web and simulated state full model for web developers. It contains concepts like post backs, view state without any single line of code.

ADVANTAGES:

  • ·        Rich server side control.
  • ·        Server controls with data binding like Grid view, list view etc.
  • ·        Supports for view state to provide state full requests.
  • ·        Event driven programming.
  • ·        Rapid application development (RAD)
  • ·        Less learning efforts.

DISADVANTAGES:

  • · No fixed predefined project architecture, everything in code behind.
  • · TESTING:- In web forms code behind ends up with lots of event handlers making automatic unit testing is an impossible task.
  • · PERFORMANCE:- View state is stored in the page itself resulting increased page size so reduced performance.
  • · LESS CONTROL OVER HTML:- The web form tags generated HTML tags for server control, integrating with java script is default.
  • · NO SEARCH ENGINE OPTIMIZATION (SEO) URLs:- URLs are pointing to fixed ASPX pages with might be decorated with some query string. They are not user friendly and affect SEO.
  • · LESS SUPPORT FOR PARALLEL DEVLOPMENT:- ASPX page are tightly coupled with code behind files. So its not possible that two different developers are working on one section means one on ASPV and one on code behind at same time.

WHAT IS PATTERN AND ARCHITECTURAL DESIGN PATTERN?
Pattern is a ready-made solution or style to develop an application. Design pattern are recognized solution to common problems defined originally by the GANG OF FOUR (GOF) patterns. Foe web we follow MVC and fro desktop and WPF we follow the MVP patterns.

WHAT IS MVC
  • ·   MVC is an architectural pattern which lets us develop an application having loosely coupling between each of these elements.
  • ·   It makes presentation and or UI ignorant of business and user interaction logic.
  • ·  Model is considered an smart and handles the business rules, logic and data and will be independent of other parts of MVC (controller and view).
  • ·  Controller receives and dispatches the request in short if handles the user interaction and input logic. It knows about both model and view.

  • ·      View considered as dumb and is an output representation of model data. It may be an excel sheet, a web page showing list of records.

  • MODEL:-
  • ·    In general model relationship the code interacts with database as well as the start of the database that is stored in front end.
  • ·    Model objects will retrieve and store the model state in the form of database.

VIEW:-
  • ·    View is the components that are helpful to display data to the user in user required format. View state provides all the GUI facility like creating text box, button, label, check box, grid view etc.  

CONTROLLER:-
  • ·    Controllers are the components that will interact with view by handling the user interaction events.
  • ·    Controller will work with model, get the data and will return to the view.
  • ·    Asp.net MVC framework is designed to support pattern based software development.
  • ·  Application developed using Asp.net MVC framework is highly testable. So Asp.net MVC Framework has become a greater framework.
  • ·    Asp.net MVC is an alternative to asp.net web form but not the replacement.

WHAT IS ASP.NET MVC
  • ·  The model view controller (MVC) architectural pattern separates on application into three main components that are the MODEL, the VIEW and the CONTROLLER.
  • ·   The asp.net MVC framework provides an alternative to the asp.net web forms pattern for creating MVC based web application.
  • ·   The asp.net MVC framework is a light weight, highly testable presentation framework that (as with web forms based application) is integrated with existing asp.net features such as master pages and member ship based authentication.
  • ·    The MVC framework is defined in the System.Web.Mvc  namespace and is a fundamental supported part of the System.Web namespace.

ADVANTAGES
  •          PROJECT ARCHITECTURE:- It enforces separation of components.
  •     TEST DRIVEN DEVLOPMENT AND REUSABILITY:- In MVC controller is a separate class so automatic testing is possible featuring Test Driven Development controllers are not bound to any specific view and so can be reused for multiple views.
  •     PERFORMANCE:- ASP.NET MVC does not have support for view state, so there will not be any automatic state management which reduces the page size and so gain the performance.
  •     FULL CONTROL OVER HTML:- ASP.NET MVC does not support server controls, only option available is using HTML input controls so we will be sure about final HTML rendered at the end.
  •     SUPPORT FOR PARALLEL DEVLOPMENT:- Here layers are loosely coupled with each other, so one developer can work on controller at the same time other o view and third developer on model. This is called parallel development.
  •      SEO, URL routing and REST:- Rich routing features lets treat every URL as a resource supporting RESTFULL interface.
  •     EXTENSIBILITY:- ASP.NET MVC supports multiple view engines like ASPX, RAZOR and if required we can create our own.
  •    EXISTING ASP.NET FEATURES:- ASP.NET MVC framework is built on top of matured Asp.net framework and thus provides developer to use many good features.


The basic difference between Asp.net Web form and Asp.net MVC is
  •       Asp.net web form uses the page controller pattern. Each page has a code behind class that acts as a controller and is responsible for rendering the layout.
  • But Asp.net MVC uses the Front controller pattern. There is a signal control controller for all pages to process web application request and facility.

FLOW OF MVC:


STEP-1:- User makes request to resource in IIS server.
STEP-2:- Request comes to controller first.
STEP-3:- Controller if necessary connects to model.
STEP-4:- Model may operate on Data base.
STEP-5:- Controller chooses appropriate view based on request action.
STEP-6:- Controller pass on the model (data) to choose view.
STEP-7:- Controller sends back the view to user.

CREATING MVC APPLICATION:
Go to Visual studioè File èNew è Project èselect visual C# from the installed template èselect ASP.NET MVC 4 web application template è type the application name then click on OK è select Basic Template or Internet Application è select Razor view engine then click on Ok.
Now the MVC application will be created. The MVC application contains following folders.
  1. App_Data
  2. App_Start
  3. Content
  4. Controllers
  5. Models
  6. Scripts
  7. Views

NOTE:-
  • What many number of classes present in the controllers folder that many number of same folder present in the view folder.
  • The view folder name should be same as the controller name.


For example if we have a folder Home in the View then we must create a controller name as HomeController in the controller’s folder.
To view the output type the class name then method mane in the browser url. 
Otherwise you can change the controller name and action name in the routeconfig.cs.
PATH:- In the solution explorer è go to App_Start è RouteConfig.cs è open it and change the controller name and action method name then run.
MVC:-
  •  Normally building apps using MVC style is difficult.
  • Using Asp.net MVC web application development with MVC pattern is simplified.
  • Asp.net MVC is provided as framework that contains libraries, runtime environment to follow the MVC flow.
  • Asp.net MVC is completely open source means you can write your own view engine, you can define your own flow for requests using routing mechanism etc.
  • If you want to add a controller of your own then go to Controllers folder Right click and click Add Controller then ok (Template is empty controller).
  • If there is no folder at your view what controller you add then right click on the method and click Add View. Provide view name, view engine and add.

CONTROLLER:
  • The controller is responsible for controlling the way that user interacts with MVC application.
  • Controller with in the MVC pattern are responsible for responding to user input, often making changes to the model in response to user input.

The typical behavior of a controller can be summarized in four main steps i.e.
  • Getting input data
  • Executing the request related action method
  • Preparing data for the view
  • Triggering the refresh of the view (response)

ACTION METHOD:
A controller exposes controller actions. An action is a method on a controller that gets called when you enter a particular URL in your browser address bar.
NOTE:
  •  ViewBag and ViewData is used to pass the data between controller to View.
  • ViewData is used from MVC-2 and ViewBag is used from MVC-3 but both are same.
  • TempData is used for pass the data from controller to another controller for only one time.
  • @ symbol indicates razor tag.

EXAMPLE:
Add  a controller (ViewbagController.cs) and write this
Public ActionResult MyViewBag()
{
      ViewBag a = 100;   // single value
      Int [ ] n = new int [ 3 ];      //array
      n [ 0 ] = 1;
      n [ 1 ] = 2;
      n [ 2 ] = 3;
      ViewBag.arrayN=n;
      Return View();
}
Add a view page (MyViewBag.cshtml) and write this code
<H4>Single value is : @ViewBag.a</H4>
<br/>
<H4> Array : </H4>
      <p>
                  @foreach (var x in ViewBag.arrayN)
                  {
                              <p> @x</p>
}
            </p>
  • WEEK TYPE:- Passing the data using ViewBag is called week type i.e. no predefined data type assign.

Var x = 100; //week type
Int x = 100;   //strong type
  • STRONG TYPE:- The value assigned in the controller and the value retrieved in view both follows same data type.

For Example
In controllers page write this
Public ActionResult myView()
{
            Int a = 10;
            return View ( a );
}
In view page writes this
<p> @model </p>

 VIEW:
  •  The view is responsible for providing the user interface to the user.
  •  It is given a reference to the model and it transforms that model into a format ready to be presented to the user.
  • Starting in asp.net MVC3 view data can also be accessed via the view bag property.

ViewBag:
To pass the data between same controllers request action and view.
TempData:
To pass data between multiple controllers (similar to temporary session). Once the view is rendered to client the value will be removed from the memory.
RAZOR:
  • Microsoft has introduced a new view engine called razor that replaces ASPX as the default view engine in Asp.net MVC3.
  • Razor represents a major improvement for developers that want a cleaner and more efficient view engine with fewer key strokes.
  • The @ symbol is used to denote a server side statement.

SOME RAZOR SYNTAX:-
  •  @ * ----------------------- * @ è used for comment a line
  • Block of statement syntax

@ {
Var x = 100;
                 }
  • Switch case syntax

@{
            var day= “ TUE ” ;
            var msg = “ ”;
            switch (day)
{
            case “MON”
            msg= “MONDAY”;
            break;
           
case “TUE”
            msg= “TUESDAY”;
            break;
           
case “WED”
            msg= “WEDNESDAY”;
            break;
}
<p> Day is : @msg </p>
}
  • Loop syntax

<p> for loop </p>
@{
            int n;
            for (n=1 ; n<5 ; n++ ){
            <p>@n</p>
            }
}
<p>while loop</p>
@{
int m = 5;
            while (m<=5 && m>=1){
            <p>@m</p>
            m - - ;
            }
}
  • Postback example

<form method=”post”>
@ if (IsPost){
<p> Hello <em> Postback request</em>, Today is : @DateTime.Now</p>
}
else
{
            <p>Hello, It is the first request..!!</p>
}
<br/>
<input type=”submit” value= “Click Me..” />
</form>

Navigation in MVC Application:
Now click here to download the complete example with code.
STEP-1:- Create a new MVC application with name Navigation.
STEP-2:- Create two folders Home and Admin in views folder and then in Home folder create three view pages i.e. Aboutus.cshtml, Contact.cshtml and index.cshtml.
STEP-3:- Go to index.cshtml and write the following code
<div>
                        <a href = “ ~ / Home / index”>Home </a> &nbsp; &nbsp;
                        <a href = “ ~ / Home / Aboutus”>About Us </a> &nbsp; &nbsp;
                        <a href = “ ~ / Home / Contact”>Contact Us </a> &nbsp; &nbsp;
                        <a href = “ ~ / Admin / Admin”>Admin </a>
                        <H2> WELCOME TO MVC NAVIGATION PAGE</H2>
            </div>
STEP-4:- Go to index.cshtml page and write the following code
            <div>
                        <a href = “ ~ / Home / index”>Back</a>
                        <H2> Hhis is Index page</H2>
            </div>
Similarly write the code for remaining two view pages (contact and about) and admin page also.

STEP-5:- Before run the application go to controllers folder and create two controller file with name HomeController.cs and AdminController.cs. Write the following code in HomeController.cs.
Public class HomeController : Controller
{
Public ActionResult Index()
{
                        return View();
}
Public ActionResult Aboutus()
{
                        return View();
}
Public ActionResult Contact()
{
                        return View();
}
}
STEP-6:- Go to Admin controller.cs and write the following code
Public class AdminController : Controller
{
Public ActionResult Admin()
{
                        return View();
}
}
Now run the application and check the navigations are working or not.



No comments:

Post a Comment