European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET MVC With Knockout.Js

clock November 21, 2024 07:36 by author Peter

Fundamentals of MVVM
Developers will soon find the MVVM design pattern in Silverlight and WPF necessary. Martin Fowler's Presentation Model, which gathers strength from MVC and MVP flexible structures, serves as the foundation for the MVVM architecture. The UI design patterns with Code-Behind are meant to be entirely or partially distinct from one another.
 
The three primary components of MVVM are Model, View, and ViewModel. When the View is totally ignorant of the model, ViewModel makes reference to it. This eliminates the developer's need to interact with the business logic interface.


The diagram above describes the situation in the best way. The Model may vary throughout the project. The View is unaware of this situation. The Model is isolated from the View. The ViewModel is a middle man for managing the binding and commands.
 
With Only jQuery on MVC
Let's talk about jQuery. jQuery has a strong binding mechanism that uses HTML tag ids, a CSS class and a HTML tag name. Values are pushed from the source object into the HTML elements, thus requiring a line of code for each mapping from the source value to the target element. It's much easier with KO. It lets you scale up in complexity without fear of introducing inconsistencies. jQuery is simple to bind with values and tags.
 
jQuery cannot serve us in the following ways:
Any source object changes will not reflected on HTML elements. (You can push values and call again.)
Any changes in the HTML elements won't be reflected on source objects.

Code:
    <h2>Using Jquery  
        Without Knockout</h2>  
    <span>StudentNumber:</span><span id="StudentNumber"></span>  
    <br />  
    <span>Surname:</span><input id="StudentSurName" />  
    <span>Name:</span><input id="StudentName" />  
    <script type="text/javascript">  
    $(document).ready(function() {  
        var student = {  
            Number: "A123456",  
            Surname: "Leon",  
            Name: "Alexander"  
        };  
        $("#StudentNumber").text(student.Number);  
        $("#StudentSurName").val(student.Surname);  
        $("#StudentName").val(student.Name);  
    });  
    </script>  

You can bind your values to HTML tags using the HTML tag's id and CSS classes. jQuery is an excellent low-level way to manipulate elements and event handlers on a web page. jQuery doesn't have a concept of an underlying data model. If you bind the values of any object like above, you will not observe any changes in the UI after any change of the Model. You must refresh web pages to observe View changes. On the other hand; if you change the HTML element's value then your model won't be fired.

What is knockout.js?

KO is not an alternative to jQuery or other js libraries (Prototype, MooTools). KO focuses on MVVM to manipulate the Model to the View from AJAX calls. KO manages between the ViewModel and View the automatic relation that is triggered by user interface calls.
 
Model: Business Logic.
View:   HTML/CSS. If you change the ViewModel's objects, the View will be effected automatically.
ViewModel: He is a middle man to observable connection Model and View because the Model doesn't have any knowledge of the View.
 
Observable and Binding: KO's focus is on the Data-Driven js concepts; in other words, any changes in the View will fire the model; also the model's changes will automatically fire the View's updates. KO is on the alert to communicate between them in both directions.

Code:
<h2>With Knockout</h2>  
<span>Student Number:</span><span data-bind="text: Number"></span>  
<br />  
<span>Surname:</span><input data-bind="value: Surname" />  
<span>Name:</span><input data-bind="value: Name" />  
<script type="text/javascript">  
var student = {  
    Number: "A123456",  
    Surname: "Leon
",  
    Name: "Alexander"  
}  
// Activates knockout.js  
ko.applyBindings(student);  
</script>  

The HTML tag binding is unable to observe the Data-Bind structure. KO concentrates on data-binding via the data-bind tag. But the preferred usage is the following. It is useful to control the View's changes for values of the Model's objects. Observable property is one of the most important things. MVVM needs to observe any changes in UI. KO will consider any changes to the View. Actually, when you edit one of those text boxes, it does update the underlying ViewModel data.

Update your ViewModel to make the Name and Surname properties observable using ko.observable:

<script type="text/javascript">  
var student = {  
    Number: ko.observable("A123456"),  
    Surname: ko.observable("Leon"),  
    Name: ko.observable("Alexander")  
}  
// Activates knockout.js  
ko.applyBindings(student);  
</script>  


Now re-run the application and edit the text boxes. This time you'll see not only that the underlying ViewModel data is being updated when you edit, but that all associated UI is updating in sync with it too.

Simple Usage Knockout on MVC
Real-World applications need to be fed from a database. So, the Model would be your application's stored data that would be implemented using a server-side technology. The View is always interested in the UI requests. The Viewmodel contains objects to manage any responses from the View. A programmer must be able to imagine how to generate a ViewModel, not only WPF but also data-driven HTML pages. Data-driven means that the implementation of the ViewModel uses JavaScript.
 
Sometimes, we don't need to implement the ViewModel with JavaScript. We can bind the server-side Model to the View. "@Html.Raw(Json.Encode(Model));" is an effective way to bind the Server-side Model to the View.

Model: public class Student {  
        public string Number {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string Surname {  
            get;  
            set;  
        }  
    }  
    //Controller:  
      
    [HttpGet]  
    publicActionResult StudentMvcWithKnockout() {  
        Student student = new Student();  
        student.Number = "B123456";  
        student.Name = "Peter";  
        student.Surname = "Scott";  
        return View(student);  
    }  
    //View:  
      
    @using System.Web.Script.Serialization;  
    @model MvcAppWithJquery.Models.Student  
    @ {  
        ViewBag.Title = "StudentMvcWithKnockout";  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
    <h2>StudentMvcWithKnockout</h2> <  
    scriptsrc = "../../Scripts/knockout-2.1.0.js"  
    type = "text/javascript" > < /script> <  
    scriptsrc = "../../Scripts/knockout.mapping-latest.js"  
    type = "text/javascript" > < /script> <  
    p > Name: < strongdata - bind = "text: Name" > < /strong></p >  
        <p>SurName:<strongdata-bind="text: Surname"></strong></p> <  
        scripttype = "text/javascript" >  
        $(function() {  
            var model = @Html.Raw(Json.Encode(Model));  
            ko.applyBindings(model);  
        }); <  
    /script>  


By calling ko.mapping in the view, we can access JSON data. But we must pass the JSON data from the controller by "return Json(StudentList,JsonRequestBehavior.AllowGet);". So we need a number of collections on ViewModel. We call "ko.applyBindings(viewModel) - so" simply using:
$(document).ready(function () { ko.applyBindings(viewModel); });
 
The $.ajax and $.getJSON methods are appropriate to get the JSON data. (Controller/Action) You can find two methods in the source code.


Code:
    // Controller  
    public JsonResult GetStudents()  
    {  
    List<Student> StudentList = newList<Student>(){new Student(){ Number="A123456", Name="Alexander", Surname="Leon"},  
            new Student(){ Number="B123456", Name="Peter", Surname="Scott"},  
            new Student(){ Number="C123456", Name="Michael", Surname="Leroy"},  
            new Student(){ Number="D123456", Name="Frank", Surname="Mill"}};  
            return Json(StudentList,JsonRequestBehavior.AllowGet);  
            }  
            // View  
            <tbody data-bind="foreach: Students">  
                <tr style="border-bottom: 1px solid #000000;">  
                    <td>  
                        <span data-bind="text: Number"></span>  
                    </td>  
                    <td>  
                        <span data-bind="text: Name"></span>  
                    </td>  
                    <td>  
                        <span data-bind="text: Surname"></span>  
                    </td>  
                </tr>  
            </tbody>  
            </table>  
            </div>  
            </form>  
            <script type="text/javascript">  
            var AppViewModel = function() {  
                var self = this;  
                self.Students = ko.mapping.fromJS([]);  
                $.getJSON('/Student/GetStudents/', function(data) { ko.mapping.fromJS(data, {}, self.Students); });  
            }  
            $(document).ready(function() {  
                var viewModel = new AppViewModel();  
                ko.applyBindings(viewModel);  
            });  
            </script>  

Review of Codes
"self.Students = ko.mapping.fromJS([]);" is an important one because "mapping from What?" is necessary. Mapping is controlled by Js. Calling'/Student/GetStudents/' we can feed the ViewModel.
You should use "$.getJSON" and "$.ajax" to get the JSON data.
Using "ko.mapping.fromJS(data, {}, self.Students);" you can fill the "self.Students" ViewModel using data that is in the JSON format.

Summary
KO can help you implement it easier and improve maintainability. Model Changes are observed by the ViewModel and updated UI parts. KO is a simple way to connect the UI from the Data Model. You can charge data procedures on KO so other js events (Click, Mouseover, Grid etc.) can be developed by using jQuery. KO is a pure JavaScript library that works with any server and client-side technology. KO provides a way to use MVVM on MVC technology. KO provides a complimentary, high-level way to link a data model to a UI.



ASP.NET MVC Hosting - HostForLIFE :: The Pipeline and Architecture of MVC

clock November 11, 2024 07:09 by author Peter

MVC is merely a design pattern used to create applications; it is not a programming language. The MVC design pattern was first used for creating Graphical User Interface (GUI) programs, but it is now also widely used for constructing desktop, mobile, and web apps. This technique is used in many programming languages, but we'll talk about it in relation to ASP.NET.

Last week one of my friends asked this question: "What is the MVC Architecture & its Pipeline?" and I am dedicating this article to him. I hope he will like this.

What does MVC mean?
In ASP.NET, model-view-controller (MVC) is the name of a methodology or design pattern for efficiently relating the user interface to underlying data models.

Understanding MVC

Model
It is responsible for maintaining the data and behavior of the application or it can be called the Business Layer. The classes in Models have properties and methods that represent the application state and rules and are called Entity classes or Domain classes, as well as these are independent of the User Interface (UI).

Models also contain the following types of logic.

  • Business logic
  • Data access logic
  • Validation logic

Model classes are used to perform the validation logic and business rules on the data. These are not dependent on the UI so we can use these in different kinds of applications. Simply, these are Plain Old CLR Objects (POCOs).

What is POCO?

The classes that we create in the Model folder, are called POCOs. These classes contain only the state and behavior of the application and they don’t have the persistence logic of the application. That’s why these are called persistent ignorant objects. POCO class is,

public class Student
{
}


The main benefits of POCOs are really used when you start to use things like the repository pattern, forms, and dependency injection. In other words – when we create an ORM (let's say EF) that pulls back data from somewhere (DB, web service, etc.), then passes this data into objects (POCOs). Then if one day we decide to switch over to NHibernate from EF, we should not have to touch your POCOs at all, the only thing that should need to be changed is the ORM.

View

This layer represents the HTML markup that we display to the user. This can be called the Display Layer. View is the user interface in which we render the Model in the form of interaction. The Views folder contains the .cshtml or .vbhtml files which clearly shows that these files are the combination of HTML and C#/VB code. In the Views folder, for every Controller there is a single view folder and for each action method in the controller, there is a view in that view folder, having the same name as that of the controller and action method respectively. There is also a Shared folder in the Views folder which represents the existence of Layout and Master Page in ASP.NET MVC.

Controller

When the user interacts with the user interface; i.e. View, then an HTTP request is generated which is in the MVC architectural pattern, handled by the Controller. So we can say that the Controller’s responsibility is to handle the HTTP request. This layer can also handle the input to the database or fetch the data from the database records. So it can be called the Input layer.

The Controllers folder contains the classes that are responsible for handling HTTP requests. The name of the controller ends with the word Controller to differentiate it from other classes, for example, AccountController, and HomeController. Every controller inherits from the ControllerBase class which implements the IController interface which is coming from the System.Web.Mvc namespace. The IController interface's purpose is to execute some code when the request comes to the controller. The look and feel of the controller is like this.
using System.Web.Routing;

namespace System.Web.Mvc
{
    {
        void Execute(RequestContext requestContext);
    }
}


There is an Execute method in the IController class that gets executed when the request comes to the controller. This method takes an object of the RequestContext class, and this class encapsulates the information about the HTTP request that matches the defined route, with the help of HttpContext and RouteData properties. The look and feel of the RequestContext class is like this.
using System.Runtime.CompilerServices;
namespace System.Web.Routing
{
    // Encapsulates information about an HTTP request that matches a defined route.
    public class RequestContext
    {
        // Initializes a new instance of the System.Web.Routing.RequestContext class.
        public RequestContext();

        // Initializes a new instance of the System.Web.Routing.RequestContext class.
        // Parameters:
        // httpContext:
        // An object that contains information about the HTTP request.
        // routeData:
        // An object that contains information about route that matched the current
        // request.
        public RequestContext(HttpContextBase httpContext, RouteData routeData);

        // Summary:
        // Gets information about the HTTP request.
        // Returns:
        // An object that contains information about the HTTP request.
        public virtual HttpContextBase HttpContext
        {
            get;
            set;
        }

        // Summary:
        // Gets information about the requested route.
        // Returns:
        // An object that contains information about the requested route.
        public virtual RouteData RouteData
        {
            get;
            set;
        }
    }
}


The code is very self-explanatory with the help of comments.

How does this architecture work?
The workflow of MVC architecture is given below, and we can see the request-response flow of an MVC web application.

The figure is very self-explanatory and shows the workflow of MVC architecture. The client, which is the browser, sends a request to the server (internet information server) and the Server finds a Route specified by the browser in its URL and through Route. The request goes to a specific Controller and then the controller communicates with the Model to fetch/store any records. Views are populated with model properties, and the controller gives a response to the IIS7 server, as a result server shows the required page in the browser.

As we know, in MVC there are three layers that are interconnected to each other such as in the figure.

Here, in MVC there is complete separation in each layer, referred to as Separation of Concerns. Now, what exactly does Separation of Concerns mean?

What is the Separation of Concerns?
Separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. A concern is a set of information that affects the code of a computer program. (Wikipedia)

MVC implements the principle of SoC as it separates the Model, View, and Controller. Following is the table that depicts the implementation of SoC and Violation of SoC in ASP.NET MVC.

Implementation of SoC Violation of SoC
Views are only for displaying the HTML markup to the browser.

When we use business logic in View then it is a violation because its sole purpose is to display the page not to execute the logic.

@if (user.Role == "Admin") { }
else { }


Controllers are just to handle the incoming HTTP request.

When we use business logic in the Controller like when the controller executes the database logic to fetch/store the information in the database, it is a violation of single responsibility principle as well.

public ActionResult Index()
{
    if (ModelState.IsValid)
    {
        dbContext.Employees.Add(model);
    }
    return RedirectToAction("Saved");
}

Use the Service layer to implement this business logic in the web application.

Models contain classes of the domain or business.

When we use ViewBag and ViewData to pass the data from controller to view instead of using ViewModels to display data in view. ViewModels are classes that bind strongly typed views. Use the Repository pattern to access the data from the database.

public ActionResult Contact()
{
    ViewBag.Message = "Your contact page.";
    return View();
}

Characteristics of MVC
These are the main characteristics of ASP.NET MVC,

  • Enables clean separation of concerns (SoC).
  • Follows the design of the stateless nature of the web.
  • Provides Test Driven Development (TDD).
  • Easy integration with JavaScript frameworks.
  • Provides full control over the rendered HTML.
  • No ViewState and PostBack events

Pipeline in MVC
We can say that the pipeline of MVC contains the following processes.

  • Routing
  • Controller Initialization
  • Action Execution
  • Result Execution
  • View Initialization and Rendering

 

Let’s understand them one by one!

Routing

Routing is the first step in the ASP.NET MVC pipeline. In fact, it is a pattern-matching system that matches the incoming request to the registered URL patterns which reside in the Route Table.

Routing is a system in which URL patterns are matched with the URL patterns defined in the RouteTable by using the MapRoute method. The process of Routing comes into action when the application starts, firstly it registers the routes in the RouteTable. This registration of routes in the RouteTable is essential because it is the only thing that tells the Routing Engine how to treat the requested URL requests. The routes are registered in the RouteConfig class App_Start file of the application. Let's have a look at it.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
        );
    }
}

The Global. asax file looks like.
protected void Application_Start()
{
    // Some other code is removed for clarity.
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

The Routing Engine is the module whose responsibility is to treat the HTTP request. When an HTTP request comes, the UrlRoutingModule starts matching the perfect URL pattern from the RouteTable, when found successfully, the Routing Engine forwards the request to RouteHandler.

In RouteHandler its interface IRouteHandler comes into action and calls its GetHttpHandler method. This method looks as below.
public interface IRouteHandler
{
    IHttpHandler GetHttpHandler(RequestContext requestContext);
}


After finding the route successfully, the ProcessRequest() method is invoked, as shown in the figure above, otherwise, user will receive an HTTP 404 error page.

Controller Initialization
While the ProcessRequest() method is invoked, it uses the IControllerFactory instance to create the controller for the URL request. The IContollerFactory is responsible to instantiate and return an appropriate controller and this created controller will become the subclass of the Controller base class.Then the Execute() method is invoked.

ProcessRequest() method looks like this.
protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
    SecurityUtil.ProcessInApplicationTrust(delegate
    {
        IController controller;
        IControllerFactory factory;
        this.ProcessRequestInit(httpContext, out controller, out factory);
        try
        {
            controller.Execute(this.RequestContext);
        }
        finally
        {
            factory.ReleaseController(controller);
        }
    });
}


Action Execution
Action Execution starts with Action Invoker. So, after the initialization of controller, it has the information about the action method, this detail of the action method is passed to the controller’s InvokeAction() method. This InvokeAction() implements the interface IActionInvoler and hence the action is selected for invoking.

public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)

After ActionInvoker, Model Binders come into action. Model binders are used to retrieve the data from the HTTP request and after taking data from it, it applies the validation, and data type conversion rules on that data. For example, it checks its validity by comparing its data type with the data type of action parameters, etc. Model Binders are present in the System.Web.Mvc.DefaultModelBinder namespace.

When Model Binders take data from the requested URL then it is time to apply restrictions on the use of that data. So for this purpose, we have an Authentication filter that comes into action and authenticates the user whether that user is valid or not. You can apply authentication by using the Authenticate attribute. This authentication is done with the help of the IAuthenticationFilter interface. So you can create your own by implementing it.

After authentication after checking it the user is valid or not, the Authorization Filter comes into action and checks the user access, which means who can use the data in which way. Authorization Filter applies to the authenticated user, it doesn’t apply to unauthenticated users. So authorization filter sets the user access for the authenticated user. You can use the authorization filter by applying the Authorize attribute at the top of the action method. And this authorization is done with the help of the IAuthorizationFilter interface. So you can implement it to create your own.

After collecting data from HTTP requests, and performing authorization on any authenticated user, now is the time to execute the action. So our Action Filters come into play. Action Filters execute with the help of the IActionFilter interface. This interface has two methods that are executed before and after the action is executed, named OnActionExecuting and OnActionExecuted respectively. I’ll post another article on “How can we create a custom action filter?”

After the execution of the Action, the ActionResult is generated. Hence the process of Action Execution is completed.


Result Execution
The “Result Execution” module executes after the execution of the module “Action Execution”, in this module Result Filters come into action and execute before and after the ActionResult is executed. Result Filters are also implemented by IResultFilter, so you can create your own result filters by implementing this interface.

As you saw in the action execution section, you have Action Result as a result. There are many types of Action Results such as ViewResult, PartialViewResult, RedirectToRoute, RedirectResult, JsonResult, ContentResult, and Empty Result. These types are all categorized into two main categories named as ViewResult and Non-ViewResult types.

ViewResult type: ViewResult is a type of result in which the View of MVC part uses means by which an HTML page is rendered.
NonViewResult type: NonViewResult is a type of result that deals with only data. Data may be in text format, JSON format, or binary format.

View Initialization and Rendering

View Engine takes the ViewResult type and renders it as a View and shows it by using IView. The IView interface looks like as below,
public interface IView
{
    void Render(ViewContext viewContext, TextWriter writer);
}

After rendering the View, it is time to make HTML Helpers that are used to write input files, create links, forms, and much more. These helpers are extension methods of the HTML helper class. Validation rules can also be applied, for example, view should use HtmlHelpers and render a form having client-side validations.


Hence this is the pipeline of MVC. We have discussed each part very thoroughly.

Conclusion

This article included the basic and foremost things to understand about MVC architectural pattern and its pipeline. If you have any query then feel free to contact me in the comments. Also give feedback, either positive or negative, it will help me to make my articles better and increase my enthusiasm to share my knowledge.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in