Translation: Using ASP. NET MVC 4, EF, Knockoutjs and Bootstrap design and development Site-6-business logic

Source: Internet
Author: User

Part 3: Design Logic Layer: core development

As mentioned earlier, our solution is as follows:


Below we discuss the structure of the entire application, separated into different layers according to the logical dependencies of the different components in the application, and the communication between the layers and the layers passes or does not pass the restriction. Hierarchies are architectural styles that address maintenance and scaling issues during the long life cycle of an application.
So, let's add a class library project to the solution named Application.common.

Application.common:

This is a class library project that provides common functionality that can be used by different business logic tiers. For example: Security, logging, tracking, verification, and so on. The components defined in this layer can be used not only by different layers, but also by different applications. For ease of use in the future, we use dependency injection and abstraction to minimize modifications in the application.

For example, in our immediate use, the validation component is used to validate the data, a custom logger to log errors or warnings.

After you add the Common class library, the solution's folder looks like this:



Application.core:

This layer implements the core processing logic of the system, encapsulating all the relevant business logic. Basically, this layer usually implements the logic of domain processing. This layer also often passes through the core layer of work units to complete the PI feature, the main goal is to clearly distinguish and separate the core areas of the logic and infrastructure specific details, such as data access and data warehousing specific technologies, such as ORM, or simple data access library, or aspect-oriented architecture and so on. By separating the core functions of the system, we can further enhance the maintainability of the system, and even replace the underlying components, and rarely affect the entire application.


Next, we'll add a class library named Application.dal in the solution.

Application.dal:

The role of the DAL is to provide data access and data persistence, maintain multiple sessions, connect to different databases, and so on. The main goal here is to wrap the EF data access context objects through interfaces and conventions so that the core layer does not directly depend on EF. The data persistence component provides data access residing within the system, as well as data access outside the system. For example, WEB services that provide services to external systems. As a result, this includes a mechanism similar to the warehousing model to support data access within the system, as well as service proxies to use the data provided by other external systems through WEB services, as well as base classes and components that can be used for all warehousing.



Next, we will add a class library named Application.repository in the solution.

Application.repository:

This class library can only be accessed through Application.manager, for each root entity object in the domain, we need to create a warehousing, basically, so-called warehousing is to encapsulate the processing logic to access the application data classes and components. Moreover, they deal with the core functions of data processing, making the entire application more maintainable and able to decouple between the Manager and the core.



Next, we need to create a class library named Application.dto.

Application.dto:

It is also a class library that contains data classes that differ from entities, where there are only properties that represent data, but there is no way to process the data to communicate between the presentation layer Applicaiton.web and the service layer Application.manager. The data transfer object is the object used to encapsulate the information used to pass data to another subsystem from one subsystem of the system. Here we use the DTO object to pass data between the Manager layer and the UI layer. The main advantage of using DTOs is that data traffic can be reduced in a distributed system, which is also an important part of the MVC pattern. We can also encapsulate the data for the invocation of a method, and often use DTOs to pass parameters when the method contains 4 or more than 5 arguments.



Next, we create the Application.manager class library.

Application.manager:

This class library is only accessed by Applicaiton.web, and for each module that we define in the manager, the main responsibility of the manager is to accept requests from the UI, pass the data to the domain object in the warehouse and process the results back to the interface layer, which is the UI Between the layers and the storage layer.

Application.web:

In the previous article, we have implemented this layer using simulated data from JavaScript. This is not only dependent on ASP. NET MVC, the interface can contain user interface components, such as html,.aspx, CSHTML,MVC and so on, it can also be any Windows application. Here the method communicates with the Manager layer, encapsulates the returned result, and chooses to display the error message on page 1 or page 2. This layer uses JavaScript to house the model in the presentation layer, but the actual data processing is sent through the AJAX request to the server processing, so the server is responsible for processing the business immediately. Instead, presentation layer processing represents a logical problem.


The best way to understand the communication between layers is to let us revisit the initial requirements.

Screen 1: Contact list-Show all contacts

1.1 The interface needs to display all the contact information in the database.
1.2 Users can delete contacts.
1.3 Users can edit contact information.
1.4 Users can create new contacts.

To populate the data in the table, when the page loads, we call Contactcontroller's Getallprofiles () method, which returns all the contact information in the database, and then returns it to the page as JSON, with the data self. The form of Profiles is bound to a JavaScript object, and the following is the definition of the Getallprofiles () method in the Contact.js code.

var Profilesviewmodel = function () {    var = this;    var url = "/contact/getallprofiles";    var refresh = function () {        $.getjson (URL, {}, function (data) {self)            . Profiles (data);}        );    

When you click the Delete button, we call Contactcontroller's Getallprofiles () method, which deletes the contact information from the database. The following is the definition of the DeleteProfile () method in Contact.js.

Self.removeprofile = function (profile) {    if (Confirm ("is sure you want to delete this profile?")) {        var id = profile. profileID;        Waitingdialog ({});        $.ajax ({            type: ' DELETE ', url: ' contact/deleteprofile/' + ID,            success:function () {self. Profiles.remove (profile); },            error:function (err) {                var error = Json.parse (err.responsetext);                $ ("<div></div>"). HTML (Error. Message). dialog ({modal:true,                   title: "Error", buttons: {"OK":                   function () {$ (this). dialog ("Close");}}). Show ();            },            complete:function () {Closewaitingdialog ();}}        );}    ;

For the Create and edit button, we only redirect to the CreateEdit page, if the ID parameter is 0 to create a new contact, for the editor, the ID is the edited contact number. The following code is the CreateProfile and Editprofile methods in Contact.js

Self.createprofile = function () {    window.location.href = '/contact/createedit/0 ';}; Self.editprofile = function (profile) {    window.location.href = '/contact/createedit/' + profile. profileID;};

The following figure shows the relationship between the main three layers.

Screen 2: Create a new contact

The interface provides a blank contact interface and provides functionality.

2.1 Users can enter the user's last name, first name, email address
2.2 Allow to add any phone number by clicking the Add Number button
2.3 Users can delete any phone number.
2.4 Add any number of addresses by clicking the Add Address button.
2.5 The user can delete any address.
2.6 Click the Save button, you can save all the information entered by the user into the database, and then go back to the Contact list page.
2.7 Click the Back button to return to the contact list.

Screen 3: Update contact information

This interface displays detailed information about the contact person.

3.1 The user can edit the contact's last name, first name, and email address.
3.2 Users can add by clicking the Add, delete number button to delete the user's phone number.
3.3 Users can add by clicking the Add, delete address button to delete the user's address.
3.4 Click Save to update the user's details to the database and return to the contact list
3.5 Click the Back button to return to the contact list

As seen in the previous implementation, the need to create and edit the same page createedit.cshtml, through the profileID to distinguish, if the profileID is 0, the new, otherwise, is to edit the existing information, the following is the implementation of the details.

In any case, when the page loads and initializes phonetype and AddressType, in the Initializepagedata () method of the Contactcontroller controller, the Createedit.js Initializes the array with the following code in the

var addresstypedata;var phonetypedata; $.ajax ({    url:urlcontact + '/initializepagedata ',    async:false,    dataType: ' json ',    success:function ( JSON) {        addresstypedata = json.lstaddresstypedto;        Phonetypedata = Json.lstphonetypedto;    }});

Then, for the edit contact information, we need to get the details, through the Contactcontroller in the Getprofilebyid () method implementation, we modify the createedit.js.

$.ajax ({    url:urlcontact + '/getprofilebyid/' + profileID,    async:false,    dataType: ' JSON ',    success: function (JSON) {        self.profile = ko.observable (New profile (JSON));        Self.phonenumbers = Ko.observablearray (Ko.utils.arrayMap (JSON. Phonedto, function (phone) {            return phone;        }));        self.addresses = Ko.observablearray (Ko.utils.arrayMap (JSON. Addressdto, function (address) {            return address;        }));    

Finally, we use two methods to save the data, if we are creating a new contact, call Contactcontroller's Saveprofileinformtion () method, otherwise call the Updateprofileinformation () method, We will revise the createedit.js as follows.

 $.ajax ({type: (Self.profile). profileID > 0? ' PUT ': ' POST '), Cache:false, DataType: ' json ', Url:urlcontact + (Self.profile (). profileID > 0? '/updateprofileinformation?id= ' + self.profile (). profileID: '/saveprofileinformation '), Data:JSON.stringify (Ko.tojs (Self.profile ())), ContentType: ' Application/js On    Charset=utf-8 ', Async:false, success:function (data) {window.location.href = '/contact ';        }, Error:function (err) {var err = Json.parse (Err.responsetext);        var errors = ""; for (var key in err) {if (Err.hasownproperty (key)) {errors + = Key.replace ("Profile.", "") + "            : "+ Err[key]; }} $ ("<div></div>"). HTML (Errors). dialog ({modal:true, Title:JSON.parse (err.response Text). Message, buttons: {"OK": function () {$ (this). dialog ("Close");}}).    Show (); }, Complete:function () {}}); 


Summarize

This is it, I hope you like this article, I am not an expert, I hope you enjoy this series and can learn something.

If you have any questions welcome to the discussion, thank you.

How to use code

From here you can download the script for the database:
Application_db.sql
To run the program in VS, you need to enable allow NuGet to download missing packages during build,

Or take a look at the link description below.


Http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages

Finally, modify the database connection string in your Application.web project.

Resources
    • http://knockoutjs.com/
    • Https://github.com/ericmbarnard/Knockout-Validation/wiki/Configuration
    • http://twitter.github.com/bootstrap/
    • Http://docs.castleproject.org/Windsor.MainPage.ashx
    • http://microsoftnlayerapp.codeplex.com/
    • Http://msdn.microsoft.com/en-us/library/ff921348.aspx

Last edited in 6:41 AM by Anandranjanpandey, version 5

Article posted: http://www.cnblogs.com/haogj/

Translation: Using ASP. NET MVC 4, EF, Knockoutjs and Bootstrap design and development Site-6-business logic

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.