ASP. NET MVC2 chapter I

Source: Internet
Author: User

Now it's time to put the frameworkInto action for realAnd see how those benefits work out inA realistic e-commerce application.

Let name our first application"Sportsstore", So the online shopping have functions as follows: a product catalog that's browsable by category and page index; a cart that visitors may add and remove quantities of products to and from; A Checkout screen onto which visitors may enter shipping details

Use the strong MVC and related technologies by doing the following:

    • Following tidy MVC Architecture Principles, further enhanced by usingNinjectAs a dependency injection (di-also known as inversion-of-control) container
      Application Components
    • CreatingReusableUi pieces with partial views and the HTML. renderaction ()Helper
    • Using the system. Web.RoutingFacilities to achieve clean, search engine-optimized URLs
    • UsingSQL Server, LINQ to SQL, And the Repository design pattern to build a database-backed product catalog
    • Creating a pluggable system for handling completed orders (the default implementation will e-mail order details to a site administrator)
    • Using ASP. NET formsAuthenticationFor security

You'll build the application in three parts:

    • in this chapter , you'll set up the core infrastructure, or skeleton, of the application. this will include a SQL database, a DI container, a rough-and-ready product catalog, and a quick CSS-based web design.
    • in Chapter 5 , you'll fill in the bulk of the public-facing application features, including the catalog navigation, shopping cart, and checkout process.
    • in Chapter 6 , you'll add administration features (I. E ., crud for Catalog Management), authentication, and a login screen, plus a final enhancement: lew.administrators upload product images.

UNIT TESTING AND TDD

ASP. net mvc is specifically specified Ted to supportUnit Testing. Throughout these three chapters, you'll see
That in action, writing unit tests for databases of sportsstore's features and behaviors using the popular open
Source testing toolsNunitAndMoq.

 

 

§ 4. 1 getting started

Creating Your Solutions and projects

New project-> choose blank solution

Then you can the solution as follows:

You can delete both ofClass1.csFiles that Visual Studio "helpfully" added.

 

§ 4. 2 starting your domain model

The domain model is the heart of the application. Create a new folder called entities inside the sportsstore. Domain project, and then add a new C # class called product.

It is hard to know how to describe your product. Let's started with some obvious one.

 
Namespace sportsstore. domain. entities {public class product {public int productid {Get; set;} public string name {Get; set;} Public String description {Get; set;} public decimal price {Get; set ;}public string category {Get; Set ;}}}
 
§ 4. 2.1 Creating an abstract Repository

Create a new top-level folder insideSportsstore. DomainCalledAbstract, And add a new interfaceIproductsrepository:

 
Namespace sportsstore. domain. Abstract {public interface iproductsrepository {iqueryable <product> Products {Get ;}}}
 
§ 4. 2.1 Making a fake Repository

Add another top-level folderSportsstore. DomainCalledConcrete, And then add to it a C # class,Fakeproductsrepository. CS

Namespace sportsstore. domain. concrete {public class fakeproductsrepository: iproductsrepository {// fake hard-coded list of products Private Static iqueryable <product> fakeproducts = new list <product> {New Product {name = "football ", price = 25}, new product {name = "surf board", price = 179}, new product {name = "running shoes", price = 95 }}. asqueryable (); Public iqueryable <product> Products {get {return fakeproducts ;}}}}

 

§ 4. 3 displaying a list of products

In this section creating a controller class and action method that can display a list of the products in your repository (initially usingFakeproductsrepository)

§ 4. 3.1 adding the first Controller

In Solution Explorer, right-clickControllersFolder (in the sportsstore. webui project), and then chooseAdd-> Controller. Into the prompt that appears, enter the nameProductscontroller. Don't check "Add action methods for create, update, and details scenarios," because that option generates a large block of code that isn't useful here.

 
Namespace sportsstore. controllers {public class productscontroller: controller {}}

In order to display a list of products,ProductscontrollerNeeds to accessProductData by using a reference to someIproductsrepository.Add a project reference from sportsstore. webui to sportsstore. domain.

 
Namespace sportsstore. controllers {public class productscontroller: controller {private response productsrepository; Public productscontroller () {// This is just temporary until we have more infrastructure in place productsrepository = new fakeproductsrepository ();}}}

At the moment, this controller hasHard-codedDependency on fakeproductsrepository. Later on, you'll eliminate this dependency using a DI container

Next, add an action method,List (), That will render a view showing the complete list of products

 

§ 4. 3.2 Setting up the default route

There's a routing system that determines how URLs map onto controllers and actions. head on over to yourGlobal. asax. CSFile

As you can see, we change it

Public static void registerroutes (routecollection routes) {routes. ignoreroute ("{resource }. axd/{* pathinfo} "); routes. maproute ("default", // route name "{controller}/{action}/{ID}", // URL with parameters new {controller = "productscontroller ", action = "list", id = urlparameter. optional} // parameter defaults );}

You might already know that. No more expain.

 

§ 4. 3.3 adding the first view

The first step is to createA master pageThat will act as a site-wide template for all our public-facing views. right-click the/views/shared folder in Solution Explorer and then choose add-> new item. gave it the nameSite. Master

We just need/views/shared/site.MasterTo exist before creating the first view. Go back to yourProductscontroller. CS file, rightclick insideList ()Method body, and choose add view.

Productscontroller'sList() Method populates model withIenumerable <product>By passingProductsrepository. Products. tolist ()ToView(), So you can fill in some basic view markup for displaying that sequence of products:

<% @ Page title = "" Language = "C #" masterpagefile = "~ /Views/shared/site. master "inherits =" system. web. MVC. viewpage <ienumerable <sportsstore. domain. entities. product> "%> <% @ import namespace =" sportsstore. domain. entities "%> <asp: Content ID =" content1 "contentplaceholderid =" titlecontent "runat =" server "> List </ASP: content> <asp: content ID = "content2" contentplaceholderid = "maincontent" runat = "server"> <% foreach (VAR product in Model) {%> <div>  

Run the application then you will see the follow picture:

 

§ 4. 4 connecting to a database

You can already display a list of products fromIproductsrepository, But it is justHard-codedList. It's time to create another implementationIproductsrepository,
This time one that connects toSQL Server database

§ 4. 4.1 defining the database schema

We'll set up a new SQL database withProductsTable and someTest Data

Create a new database calledSportsstore, And the coloumns as follows:

And then fill the test data:

Here I generate the data codeMygeneration:

-- | -------------------------------------------------------------------------------- | [Products]-backs up all the data from a table into a SQL script. -- | begin transactionset identity_insert [products] oninsert into [products] ([productid], [name], [description], [category], [price]) values (1, 'kayak ', 'A boat for one person', 'watersports ', 275); insert into [products] ([productid], [name], [description], [category], [price]) values (2, 'lifejacket ', 'proteve VE and fashionable', 'watersports', 48); insert into [products] ([productid], [name], [description], [category], [price]) values (3, 'soccer ball', 'fifa-approved', 'soccer', 19 ); insert into [products] ([productid], [name], [description], [category], [price]) values (4, 'Corner flags ', 'Give your playing field that professional touch', 'soccer', 34); insert into [products] ([productid], [name], [description], [category], [price]) values (5, 'stady', 'flat-packaged', 'soccer', 79500); insert into [products] ([productid], [name], [description], [category], [price]) values (6, 'thinking Cap', 'Improve your brain', 'chess ', 16 ); insert into [products] ([productid], [name], [description], [category], [price]) values (7, 'unsteady chair ', 'secretly give your opponent a disadvantage', 'chess ', 29); insert into [products] ([productid], [name], [description], [category], [price]) values (8, 'human chess board', 'a fun game for the whole extended family ', 'chess', 75 ); insert into [products] ([productid], [name], [description], [category], [price]) values (9, 'bling-bling king ', 'Gold plated ', 'chess', 1200); Set identity_insert [products] offif @ error <> 0 rollback transaction; else commit transaction; go -- | begin --------------------------------------------------------------------------------
 
§ 4. 4.2 Setting up LINQ to SQL

To avoidManual SQL queries Or stored procedures, Let's set up and use LINQ to SQL. You 've already definedA domain entityAs a C # class (Product); Now you can map it to the corresponding database tableAdding a few new attributes.Add an Assembly reference from the sportsstore. Domain projectSystem. Data. LINQ. dll.

 

Tip:Here, you have to specify an explicit name for the table, because it doesn't match the name of the class ("product "! = "Products"), but you don't have to do the same forColumns/Properties, Because their names do match.

 

§ 4. 4.3 creating a real Repository

Add a new class,Sqlproductsrepository,Sportsstore. domain's/ConcreteFolder:

Namespace sportsstore. domain. concrete {public class sqlproductsrepository: iproductsrepository {private table <product> productstable; Public sqlproductsrepository (string connectionstring) {productstable = (New datacontext (connectionstring )). gettable <product> ();} public iqueryable <sportsstore. domain. entities. product> Products {get {return productstable ;}}}}

Back inSportsstore. webui, Make productscontroller referenceSqlproductsrepositoryInstead of fakeproductsrepository by updatingProductscontroller's constructor:

Public productscontroller () {string connstring = "Data Source = (local) \ sql2005; initial catalog = sportsstore; Integrated Security = true;"; productsrepository = new sqlproductsrepository (connstring );}

Run it, and show

 

Let's go to next section ~!

Related Article

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.