Creating First application in ASP.NET MVC ~ MiTechDev.com

Thursday, 24 March 2016

Creating First application in ASP.NET MVC

21:21:00 Posted by raviteja swayampu No comments

First MVC Application for begineers:

Hi Guys welcome again.This article is for absolute beginners.In this Article we are going to create a simple application.By the end of this tutorial you can get basic flow between Controller,Model and View.If you new to ASP.NET MVC it is better to start from beginning please go through my previus post one then you will get what is ASP.NET MVC and why we need it.pls go through the links below
Before going to create a sample application we have to understand the basic folder structure of the ASP.NET MVC application.

Topics we are going to cover this tutorial are:
  • Basic folder structure.
  • Creating Model,view and controller
  • routing in MVC
  • Control flow in ASP.NET MVC application.
I am going to explain this in step by step manner..
step 1:
  • open visual studio in your PC or Laptop.(i hope you have vistual studio 2015 installed in your system if you have older version of visual studio no problem.but i am going to explain this tutorial by using VS2015).
  • click on 'New Project'.then a window will appear like below choose 'Installed-->Templates-->Visual C#-->web' from left then select  "ASP.NET Web Application" template.


  • Then give name for application as "sampleapp" and click OK. then



select Empty template and check the 'MVC' checkbox below and donot check "Add unit tests" we will learn about unit tests in future.now we created a application.

Note: Above are the some predefined templates provided by visual studio.These templates gives some code for application (need not to write every thing from scratch).We can select "MVC" template from the above but it is good to start from the Empty template for engineers.

Basic Folder Structure of ASP.NET MVC:

The folder structure of MVC application is look like this..


AppStart: This folder consists of application level code.for example if you want to change the default page of your site like that. This folder generally contains two files "routing.cs","bundle.cs".
routing.cs contains the routing information and bundle.cs contains bundles it is used to increase the application performance using "bundling and minification technique".we will talk about this two files in future in detail..
Controllers: This folder consists of controllers of the application nothing but '.cs' files.Controllers contains business logic of the application and these are also responsible for routing.
Models: This folder contains database logic .
Scripts: It generally contains scripts required for the applications like ".js " files..and other client side scripting files.
Views: Views folder contains the UI logic (presentation logic) of application.we must place the views files in this folder only because ASP.NET MVC execution engine check this folder for required view files when client requested a page.

Note: It is not compulsory to place respective files in respective folders. but it is better to be place for development and easy to recognize code.

Control flow in MVC:

When a client requests a page in ASP.NET MVC it goes to the controller. Controller is the responsible for the request/response in MVC. It requests the model for data. Model will communicate with database and gets data and send back to controller.finally controller send the data to view for display.If user gives any data in View it comes to controller and send to model for saving in database.
In this way data in MVC flows. Here controller is responsible for everything. Controller contains the business execution logic of the application.

Creating a Controller in ASP.NET MVC:

right click on Controller folder-->Add-->Controller. then a window will appear and choose "MVC5 Empty Controller" click Add button and give name for the controller as HomeController.

Note: Controller class is post-fixed with "Controller" word this is because to differentiate the normal model class files with controller classes.ASP.NET MVC execution engine knows it is a controller class by seeing it's post-fix.

Then visual studio generates the following code of controller

Every controller class we write in the application must be derived from the "Controller" namespace.Because it contains the functionalities(properties and method) for the controller.
In above HomeController we have created a "ActionClass"(index) of type "ActionResult".Which handles the routing(request first come to controller and from controller to action method). Herewe returned a View(). controller send the data to view using "return View()". In view method we can pass the name of the View we created other wise it assumes that the view will be with the name of the Action method like "Index view".

Creating a View in MVC:

right click anywhere in the action method(from starting parenthesis to ending parenthesis)-->click add view

here we cal also select different templates like create/edit/delete/details/list etc(those templates are useful for scaffolding we will discuss about it later).here i am selecting 'Empty' template.
then a view created with following code..


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

just erase the above code and write an "actionlink" like below

<h2>
@Html.ActionLink("Link to another page","SampleAction",new{@id='lnktest'})
</h2>
This is action link in MVC(like anchor tag in html but it add some extra functionalities). This method require three parameters 1.Link text, 2.Action methos name that where we want to navigate, 3.html object reference (used to specify class name and id names for action link). just save and run the application...by pressing
the output of the application is look like this...
we have successfully created our first application...
Now i will show you data flow between model,view and controller...
Here my requirement is when i click on the above link another page should open and it should contains sample user details
for that i will create one model class and data source for the user and finally i will send that data to the view

Creating Model in ASP.NET MVC:

right click on Models folder-->Add-->class then a "Add new item window" will apper.In that select  "class" and name it "user.cs".

public class user
    {
        public int id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string designation { get; set; }
    } 

create a data source in the controller like below

using sampleapp.Models;  //must add the namespace to access the model classes

namespace sampleapp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult SampleAction()
        {
            List<user> lst = new List<user>()
            {
                new user { id=1,firstname="ravi",lastname="teja",designation="developer"},
                new user { id=2,firstname="simha",lastname="veer",designation="B.Tech"}
            };
            return View(lst);
        }
    }
}

here i created a data source for the view using List<> and passed the data to the view using View(lst) method. now create a view for the "SampleAction" method. right click on action method-->addview.
Note:before doing anything just build the solution once goto menu-->build-->build solution.


click add to create view.
modify the view code like below

@model IEnumerable<sampleapp.Models.user>   
@{ 
    ViewBag.Title = "Person details"; 

<h2>Person details:</h2> 
<table> 
    <tr> 
        <th> 
            @Html.DisplayNameFor(model => model.firstname) 
        </th> 
        <th> 
            @Html.DisplayNameFor(model => model.lastname) 
        </th> 
        <th></th> 
    </tr> 
@foreach (var item in Model) { 
    <tr> 
        <td> 
            @Html.DisplayFor(modelItem => item.firstname) 
        </td> 
        <td> 
            @Html.DisplayFor(modelItem => item.lastname) 
        </td> 
   
    </tr> 


</table>

then run the code and see the output using "F5"...
I hope u understand the tutorial..if any queries let me know through comments..i am ready to help you.

0 comments:

Post a Comment