ASP.NET MVC Overview

ASP.NET MVC Overview

ASP.NET MVC Overview

MVC is designed so that programmers, designers and testers can work independently.

With MVC architecture, we divided the app into three parts that depend on each other and work together to view a dynamic web application. “View“ will never know how to access the data, because it's a job of „Model“. The controller does not know where to place the error message or how to paint it, because it's a job of „View”. This isolation helps to create a web application and makes it easy to maintain and make any changes. ​

Model-view-controller (MVC) is an architectural pattern that divides the application into three interconnected parts. The name comes from the "Model", "View" and "Controller" form. This design helps different teams work on the same project within a complex programming environment. For example, teams of designers, developers, and testers can work on the same project without conflicting in the code.

Mvc 5. Model View Controller

Picture 1. MVC Pattern

Controller

To understand the controller it would be best to explain the process of retrieving the site. During the HTTP request in MVC architecture through defined routes the data is sent to the controller and it returns certain content to us. The routes are defined in the file App_Start/RouteConfig.cs. The first time the application starts, the basic route will be started. It leads to the controller „Home“ and its methods „Index“. In this example, we will map a new route „MyRoute“ (code shown in the example 1). If we write the URL of our route in the internet browser, we'll get a error. Whitout created Controller the routes do not work. In the controller, we determine what route will be returned to the user.

using System.Web.Mvc;
using System.Web.Routing;
namespace WebSkProject
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            // My Route
       routes.MapRoute("MyRoute", "my/{name}", new {controller=" MyRoute ", action="Search", name=""});
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
​​​​​​​
}

Example 1. RouteConfig code

 

In the following example we will see two methods which give the user different actions. The first method in the controller returns an variable „name“ which we can write in the URL, and the other one prints the default text.

using System.Web.Mvc;
namespace WebSkProject.Controllers
{
    public class MyRouteController : Controller
    {
        // GET: MojaRuta
        public ActionResult Search(string name)
        {
            var message = Server.HtmlEncode(name);
            return Content(message);
        }
        public ActionResult Other()
        {
            return Content("lorem ipsumlorem ipsumlorem ipsum");
        }
    }
​​​​​​​
}

Example 2. MyRouteController

 

When we open in the internet browser e.g: /Home/About HTTP request via the route comes the controller actually on method within that controller that can return various types of data. For this example returns „View“ which displays information about the website. Controller does not really know what's in „View“, it is clearly set to him that the user by calling a specific route, want to have a specific view on the screen. Web site data is not written in „View“ component. This information is written in „Models“, “View” task is to connect to the model and get information requested by the user, and by using HTML, CSS and some other tools for the layout of the website displays to the user.

using System.Web.Mvc;
using WebSkProject.Models;
namespace WebSkProject.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
 var student = new Student() {StudentID= 1, FirstName="Adam", LastName="Mirković" };           

            return View(student);
        }
    }
​​​​​​​}

Example 3. Controller code

 

„HomeController“ will be on the route /Home/Indeks return „View“ which is written in the folder Views/Index.cshtml. That „index“ document contains the HTML code and is not related to the model. By calling that route, a statistical website will be displayed to the user. The same controller by calling the route /Home/About will return „View“ student model. In the controller we created the student who is called Adam Murphy and for value id have 1. „Model“ component of this controller is shown in Example 3.

Model

A model is a component that contains all data sent to the controller and displayed on „Views“. „View“ must have a defined model in the header

@model WebSkProject.Models.Student  

...and that "View" must be forwarded to the controller

public ActionResult About()
        {
   var student = new Student() {StudentID= 1, FirstName="Adam", LastName="Murphy" };           

            return View(student);  }

It is important to note that the controller is not responsible for what is happening on „View“ with the Model. With the Razor Engine you can access the model and all its features and methods.

namespace WebSkProject.Models
{
    public class Student
    {
        public int StudentID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
    }
​​​​​​​
}

Example 4. Model code

 

View

„View“ is basically HTML code. File extension is “cshtml” but syntax is the same as HTML. Razor syntax is used for writing C# . Razor syntax allows you to write C # code within a web site. When the server reads the page, he runs C# code first, before it sends the page to the browser. By running on the server, the code can perform tasks that can be a lot more complex to do using client content alone, like accessing server-based databases. From the browser's perspective, client content that's generated by your server code is no different than any other client content. In „Views/Shared“ folder is all code shared with the application. „Layout“ is template which contains documents that share a code. In the „Views“ folder each controller has its own folder where the files must match the methods within the controller.

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>
<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
 ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
​​​​​​​
</div>

Example 5. Home/Index HTML code
 

@model WebSkProject.Models.Student 
@{
    ViewBag.Title = "About";
}
<h3>@ViewBag.Message</h3>
<div>
    ID: @Model.StudentID <br/>
    Ime: @Model.FirstName <br/>
    Prezime: @Model.LastName
​​​​​​​
 </div>

Example 6. Home/About „View“ code

 

In "View" you have to call on the model we use. We must use Razor syntax for writing c# code. With “@” sign mark the beginning of the c # code. In this example we use a “Model” which contains the property of our student (id student, name and last name). To the user who requested the route /Home/About the following view will appear on the screen:

Home/Index HTML code

Picture 2. View for route /Home/About>

 

Entity Framework

Entity Framework is a part of the Net.Framework. EF allows us to access relational databases using strongly typed C Sharp core, or Visual Basic code or really any .Net language. There are three ways to access databases. Shema first, Model first and Code first. I’m working with classes to talk the Entity Framework, I don’t have to worry about SQL connections, SQL commands, SQL parameters… There’s a few different ways to get started with the Entity Framework. One approach is called the Shema First approach. In this approach, you open up a graphical designer in Visual Studio, you point it to an existing database, and it can import the database schema and generate all the classes you need to query and update that database. Another approach is a Model First approach. We use the same graphical designer in Visual studio to draw a conceptual model for applications, so what classes do I want. Then EF generate both my class definitions and database schema. Finally, there’s a Code First approach you can take with EF. In this approach, it is necessary write C Sharp classes and the EF can use those class definitions to create a database. It will do that either using conventions like naming conventions. Naming conventions may make some things work if we write them in the right way. "Entity Framework" knows how to work with various types of databases (SQL Server, SQL Compact, Oracle, DB2…). We can create an application without much worries about the database type. You can read more about EF in the article Entity Framework Overviw

Posted by Josip Golubovic

Josip Golubovic

Related Posts

Comments

comments powered by Disqus