Published: 02 Dec 2009
By: Xianzhong Zhu
Download Sample Code

In this two-part series, you will learn how to a typical front end of an E-commerce system using the great Microsoft ASP.NET MVC 1.0 framework. In the first part, we will focus upon the following points: system design, functionality design, architecture design, and database design, etc. in the second part, we will discuss the detailed coding related things.

Contents [hide]

Build a Front End of an E-commerce System Using ASP.NET MVC Framework Series

  • Part 1 Build a Front End of an E-commerce System Using ASP.NET MVC Framework Part 1
  • Part 2 Build a Front End of an E-commerce System Using ASP.NET MVC Framework Part 2
  • Model Design

    First of all, let's start with the model design.

    The model tier undertakes the task of encapsulating the data tier. Specifically, in the modal layer, we need to set up the data model using some techniques, or even build helper classes to further modularize the design. In real cases, you can use any design pattern, methodology, and/or custom process to accomplish the creation of the model. In this system, we will fall back upon the popular LINQ to SQL to create the data model.

    Creating the Data Model Using LINQ to SQL

    To facilitate the database operation, we are to create a LINQ to SQL class named BookShop.dbml. Below list the related steps:

    1. In Solution Explorer, right-click the Models folder and then click Add New Item.
    2. Under the Visual Studio installed templates, click LINQ to SQL Classes.
    3. In the Name box, enter a name for the database model. Here, we enter the name BookShop.dbml.
    4. Click Add. The Object Relational Designer is displayed.
    5. In Server Explorer (Database Explorer), under Data Connections, expand the database file node (in this case BookShop) and then the Tables node.
    6. Drag all the tables into the left side of the O/R Designer, and all the stored procedures into the right side.
    7. Save and close the BookShop.dbml model file.
    8. Compile the application.

    With the above steps accomplished, you may find in the file BookShop.designer.cs dozens of line of code which appropriately encapsulates the related typical CRUD operations with all the tables, as well as with all the stored procedures. For brevity, we don't enumerate the code any more, and instead, we shift our attention to look into the custom helper class in the model layer.

    Designing a Helper Class

    In real scenarios, it is often useful to extend the LINQ objects created from the DBML to add some necessary properties and methods since the LINQ to SQL class only provides the basic CRUD support. This will save you from writing the code into your controller actions and views.

    In our system, to facilitate the controller's invocation, we are to design a helper class named BookStore which further extends or abstracts the basic data operations in file BookShop.designer.cs.

    To facilitate the manipulation of the order detail data, we create another helper class - OrderDetails. Below lists all its related code:

    Listing 1: Code for the helper class BookStore

    In the above method GetOrderDetails, we first call method OrdersDetail of the BookShopDataContext object to obtain the all the order detail info. Then, we create an instance of the sub class OrderDetails and specify the values of each property using the returned data of method OrdersDetail. Finally, we return this instance of class OrderDetails for later invocation of action orderdetails.

    Besides, we've also defined several helper methods related to the shopping cart or the order data, such as TransplantShoppingCart, GetShoppingCartId, AddItemtoShoppingCart, CountShoppingCartItem, DisplayShoppingCart, ShoppingCartTotalCost, ShoppingCartRemoveItem, ShoppingCartUpdate, PlaceOrder, and GetUserOrders. However, due to limited space, we are going to leave out the related detailed examinations and in later contents, may still refer to some of them.

    Next, let's focus upon the controller related coding.

    Controller Design

    In ASP.NET MVC framework, the controller bears the responsibility of the application logic for manipulating the model, handling user interactions, and choosing the view to display on the client side. The controller is like the glue that pieces the model and views together. Figure 1 illustrates a rough schema of the ASP.NET MVC framework.

    Figure 1: A schema of the ASP.NET MVC framework

    A schema of the ASP.NET MVC framework

    In essence, the controller is just a class object, which inherits from an already-implemented Controller class (which in turn inherits from the System.Web.Mvc.IController interface). A typically implemented controller will contain one or more action methods.

    The actions in the controller use the model that you created previously to provide access to the data and to enforce validation rules, check constraints, and provide an object-oriented representation of the data and methods for binding to the views. Thus, the controller serves as a mapping layer that creates a relationship between the models and views.

    In our system, we have designed two controller classes, i.e. HomeController and UserCenterController, which perform the general book business and user data related view dispatch, respectively.

    Next, we are going to discuss each of the actions defined in the two controllers.

    The Controller HomeController

    There are totally twenty-two actions defined in the controller HomeController class, as are listed in the following table. This table enumerates the controller actions that are needed to support the functionalities that we are designing. The first column of the table below lists the action method name, the second column lists the roles that will have access to the action, and the last column lists the parameters for that action.

    Table 1: Actions defined in the controller HomeController

    Action Method

    Security

    Parameters

    Index

    Any user

    --

    ShoppingCart

    Valid user

    --

    AddToCart

    Valid user

    int id

    Search

    Any user

    string id

    OrderList

    Valid user

    --

    Reg

    Any user

    --

    BookDetails

    Any user

    int id

    BookList

    Any user

    string id

    LogOut

    Valid user

    --

    login

    Any user

    --

    orderdetails

    Valid user

    int id

    Checkout

    Valid user

    --

    Since these actions are very important to this system, it's necessary to dissect each of them one by one.

    1. The Index Action

    The first action method you'll implement is used to display the home page. This action takes no parameters:

    In this action, we first create an instance of class BookShopDataContext which encapsulates the data access tier of the system. Then, by calling method MostSoldBooks we obtain the most sold books info (i.e. with the sales quantity standing at top six) and store it into the dictionary structure ViewData. Finally, by invoking return View(); the user will be redirected to view Index which will receive the ViewData object as the data source.

    Note

    The ViewData property is used to store and transmit data from the model and controller to the view for rendering. It can either be used as a Dictionary object, such as: <%= ViewData[“text”] %> or as a typed model object, such as: <%= ViewData.Model.CustomerID %>.

    2. The ShoppingCart Action

    The ShoppingCart action is even simpler, shown below:

    Obviously, the ShoppingCart action can do nothing but execute one line of code: return View();. This means the current user is quickly navigated to the view page ShoppingCart.aspx.

    3. The AddToCart Action

    This action is used to obtain the shopping cart ID, then adds shopping info into the cart, and finally redirects the user to the shopping cart page AddToCart.aspx.

    4. The Search Action

    This action is used to retrieve the specified kinds of books, with the related code listed below.

    In detail, first pick out the book name string from inside the browser's Cookies; then, call method SearchBook in the data access layer by passing the book name string as the argument and write down the returned value; later, assign the returned data to the ViewData structure; and at last, navigate the user to view Search.aspx.

    5. The OrderList Action

    The following gives the code for action OrderList:

    As is shown above, first judge whether the current user has logged in by checking out the Session structure. If the user has not assigned in, then redirect him to the login page. If the user is valid, then by resolving the Session structure obtain the ID of the user and pass it as the parameter to the method GetUserOrders of the data access layer. Finally, store the searching results of method GetUserOrders to the ViewData structure and redirect the user to the OrderList.aspx page.

    6. The Reg Action

    The following gives the complete code for action Reg:

    As is shown above, invoking this action will directly lead the user to the registration page Reg.aspx.

    7. The BookDetails Action

    The following gives the complete code for action BookDetails:

    This action is also simple: by calling method BookDetail in the data access layer, get the special book detail data, then store them into the related dictionary position, and finally redirect the user to the view BookDetails.aspx.

    8. The BookList Action

    The following gives the code for action BookList:

    In the above code, first resolve the parameter id to get the CategoryID parameter. Then, by invoking method BookByCategory, get the book data belonging to the specified category. And then, add the data to the ViewData structure. At last, redirect the user to view BookList.aspx.

    9. The LogOut and login Actions

    The following lists together the code for the two actions LogOut and login:

    These two actions are both simple and similar in implementation logics: invoking the two actions will directly lead the user to the logout and login pages, respectively.

    10. The orderdetails Action

    This following gives the code for action orderdetails:

    As is apparently seen, the orderdetails action performs the following tasks: invoke the method GetOrderDetails of the helper class BookStore; then, persist the returned data to the ViewData structure; and at last, redirect the user to the view orderdetails.aspx.

    11. The Checkout Action

    This following gives the code for action Checkout:

    Here, the Checkout action first get the ID value that identifies the current shopping cart by calling method GetShoppingCartId of the helper class BookStore; then pass this ID value as the parameter to another helper method DisplayShoppingCart to obtain all the current cart related data; and finally, redirect the user to the view Checkout.aspx.

    Next, let's turn our attention to another controller - UserCenterController.

    The Controller UserCenterController

    There are totally four actions defined in the controller UserCenterController class, which are still listed in the table form, as follows.

    Table 2: Actions defined in the controller UserCenterController

    Action Method

    Security

    Parameters

    Default

    Valid user

    --

    ModPwd

    Valid user

    --

    ModUserInfo

    Valid user

    --

    SuccessEdit

    Valid user

    --

    Since the four user-related actions are all simple to understand with short code, and especially we are not going to put too much emphasis on the user data related coding, we elide discussing them.

    Till now, we've finished discuss about the controller's action design. Then, from the next section we start to delve into the view related programming.

    View Design

    Under the ASP.NET MVC design model, .aspx files are typically stored in the Views folder. In this system, we have divided the views into three parts located under the three different folders respectively: Shared, which contains multiple file-sharing custom controls and master pages; userCenter, which contains user-related web pages, such as user information, password, etc.; the rest web pages are put under the Home folder. As is known, the Home folder and the Shared folder have been automatically created by the system; we have to, however, manually add the userCenter folder to the Views folder. First let's start with the homepage view.

    The Index.aspx View

    The homepage of the book sales system is achieved through view Index.aspx, which supports login functionality, search functionality, the most popular books functionality, etc. Figure 2 indicates one of the running time snapshots of this view.

    Figure 2: The running time snapshots of the Index.aspx view

    The running time snapshots of the Index.aspx view

    In view Index.aspx, we've utilized two user controls, i.e. BookNav.ascx on the left side acting as the book category navigation, and Search.ascx on the top line used to retrieve the user interested books. In the middle prominent position, we use the DataList control to display some of the best-selling books.

    If the user succeeds in logging into the system, his ranking level will be shown and an entrance to the user management center also appears; or else, he has to login or registers again. Since the login and registration operations are both the common routines, we leave them to the readers to look into referring to the source code.

    Next, let's look into how the most popular books are displayed. The related markup code is as follows:

    Listing 2: Show the best-selling books

    Using the ItemTemplate template of the DataList control, we display the snapshot of each book. At the same time, we attach a related URL to each image. So, when the user clicks the book image, he will be redirected to the page corresponding to the detail info of his favorite book.

    Now, let's continue to follow up the scent to see how the data required by the DataList control are passed:

    Some readers may ask where the ViewData["MostSoldBooks"] come from? Do you remember the Index action we discussed earlier? The answer right lies in it, where we invoked the method MostSoldBooks of object BookShopDataContext, and then assigned the returned value to the ViewData structure. Till now, you may have gained a deep insight into how the most popular books related data are displayed on the homepage.

    Additionally, you can easily see that we've applied the ASP.NET server control Image to display the book snapshot. In this system, we keep this kind of image files in an independent folder (\Content\UpFileImages) of the website.

    Next, let's research into the user control Search.ascx. This control only implements the basic searching support by book name. The following gives its behind-code:

    As you see, here we first save the user-entered searching key, i.e. the book name, into the Cookies object. Then, we reconstruct a URL string with the book name as the parameter. Finally, we redirect the user to the Search.aspx view that will show the searching results. As for another user control BookNav.ascx, we'll discuss it shortly afterwards.

    The Search.aspx View

    The Search.aspx view is mainly used to display the searching results. Figure 3 indicates one of the running time snapshots when the user enters the searching key asp. As you see, the user can be redirected to the related book detail view by clicking the title link or decide to buy the book by clicking the link Add to the shopping cart.

    Figure 3: The running time snapshots of the Search.aspx view

    The running time snapshots of the Search.aspx view

    Now, let's first look into how the data are passed into this view.

    You may remember earlier that, when the user clicks button Search on the home page, the action Search is invoked, and then the structure ViewData["SearchBook"] is filled with the searching result associated data. Now that the data come, we bind them to the DataList control and update it.

    Now, let's take a look at the related markup code, as shown below:

    Listing 3: Using the DataList control to show the general book info

    To facilitate the layout, we introduce the <table/> element inside the template ItemTemplate of control DataList. As you see, when the user clicks the link Add to the shopping cart at the bottom, the action AddToCart will be triggered with the current book ID as the argument. Then the user will be navigated to another view AddToCart.aspx.

    The BookList.aspx View

    This view, located under the ~/Views/Home folder, allows the users to view book categories and related book summary info, and buy the books, as well as directly jump to the book detail info view. The screenshot of the page, shown in Figure 4 below, demonstrates the contents when the user clicks the Computer link.

    Figure 4: The screenshot of the BookList.aspx view

    The screenshot of the BookList.aspx view

    As is shown in the above figure, when the user clicks his interested book category, the right part of the page will show the related general book info, i.e. the book cover snapshot, price, link to the book detail view, and link to the shopping cart.

    In designing this page, we use a user control BookNav.ascx to display all the book categories. In detail, it uses the ASP.NET server control DataList to list the general info (including the book cover snapshot) of each of the books belonging to the specified category. Note that the category argument is obtained through Request.Params[“CatID"].

    Next, let's look at the behind code of the user control BookNav.ascx, as shown below:

    Listing 4: Listing 4: the behind code of BookNav.ascx

    In the above code, first through Request.Params["selection"] ascertain the value of the property SelectedIndex of the DataList control. Then, by directly invoking method ListBookCategory in the model layer, get data that will be used to populate the DataList control. Finally, assign the data to the property DataSource of the DataList control, and by calling its method DataBind to achieve the data binding which results in the data refreshing on the screen.

    For the rest things about the user control BookNav.ascx, we select to elide them. Readers can refer to the source code. So, let's shift our attention to the behind code of the BookList.aspx view, as follows:

    Herein, all should be thanks to the ViewData object. It serves as a broker passing data from the data access layer to the view. As is indicated, by obtaining data from inside the ViewData dictionary, we assign the data to the data source of the DataList control MyList, and in the end display the special category of book info on the screen.

    The BookDetails.aspx View

    For now, you have seen, wherever in this system, whether you click the book title or related snapshot you will be navigated to the book detail view-- BookDetails.aspx. Figure 5 shows one of the related running time snapshots. In this page, all the book related info is shown. When the user clicks the link Add to cart, he will be also navigated to another view.

    Figure 5: The screenshot of the BookDetails.aspx view

    The screenshot of the BookDetails.aspx view

    Since the BookDetails.aspx view is also easy to understand, we continue to omit the detailed discussion to leave space to other parts.

    The Shopping Cart Related Views

    The shopping cart module is of drastic importance in this system, which mainly relates to three views, i.e. AddToCart.aspx, ShoppingCart.aspx, and CheckOut.aspx.

    When the user clicks the Add to cart alike buttons on any pages, the view AddToCart.aspx will be invoked. It's noticed that, however, view AddToCart.aspx renders nothing on the screen, but be quickly redirected to another view. For this, you can refer to the following:

    Listing 5: There will be nothing rendered in view AddToCart.aspx

    OK, let's follow up the scent to take a look at action ShoppingCart to see what will happen.

    Nothing peculiar, isn't it? The user continues to be navigated to another view ShoppingCart. Although the above two parts of code are with none parameters, the related data has already been added to the shopping cart before view AddToCart is redirected (you can refer to the action AddToCart to find this).

    Now, let's continue to examine the ShoppingCart.aspx view. Figure 6 shows one of the running time snapshots of this view.

    Figure 6: The ShoppingCart.aspx view at the running time

    The ShoppingCart.aspx view at the running time

    As you may have found out, the ShoppingCart.aspx view accomplishes the basic functionality of shopping. When the user clicks button Add to cart, he will be redirected here. You can change the quantity of the books you want to buy. As soon as the user click button Update the cart, the contents inside the cart will be changed accordingly. And of course, you can delete the specified books that you tick off.

    Let's first look at the Page_Load event related code:

    Listing 6: The Page_Load event code in view ShoppingCart.aspx

    In the above code, we use the DataGrid control to display the shopping chart info that is obtained from view AddToCart.aspx. When we want to update the contents in the cart, the following code will be invoked:

    Listing 7: Update the contents in the shopping cart

    The interesting point here is to call method UpdateShoppingCartDatabase. The following lists the key points this method performs:

    1. By calling the method GetShoppingCartId of the helper class BookStore, get the cart ID.
    2. Iterate through the DataList control MyList to update or remove the items that the user modified.

    In between the above lines of code, you can easily see that we've resorted to the FindControl method to find the related controls and obtain relevant data, as well as used the two methods, i.e. ShoppingCartRemoveItem and ShoppingCartUpdate of the helper class BookStore, to succeed in deleting and updating the items.

    When the user clicks button Check out and if the shopping chart is not empty and the user has logged in, then he will be navigated to the CheckOut.aspx page; otherwise, he will be forcibly redirected back to the login.aspx view.

    Figure 7 illustrates one of the snapshots of the view Checkout.aspx. This view is easy to understand, with all the order info and the total price listed.

    Figure 7: One of the snapshots of the view Checkout.aspx

    One of the snapshots of the view Checkout.aspx

    Now, let's look into the event Page_Load related code:

    Listing 8: The Page_Load event code in view Checkout.aspx

    Apparently, the DataGrid control MyDataGrid is filled with data from the ViewData structure which has already been populated in the action Checkout. And also, the total price is calculated and shown on the page.

    Now, when the button Submit is clicked, the following code will be invoked:

    Listing 9: The button Submit related code

    As just a demo application, we've only called method PlaceOrder of the helper class BookStore to change the related order data in the backend database and finally show a corresponding prompt.

    Note

    In practical scenarios, the user may be redirected to some online payment systems related views.

    At last, let's look at the order inquiry related views.

    The Order Inquiry Related Views

    The order inquiry related module mainly involves two views, i.e. OrderList.aspx, and OrderDetails.aspx. With this module, the users can expediently find out all their order info. When the user clicks the hyperlink Order Inquiry on top of most of the views he can enter into the OrderList.aspx view, as is shown in Figure 8. Of course, the prerequisite is that the user has already assigned in; or else, he will be forcibly redirected back to the login.aspx view.

    Figure 8: One of the running time snapshot of the OrderList.aspx view

    One of the running time snapshot of the OrderList.aspx view

    As shown in the above figure, when the user clicks each item related link Show Details he will be leaded into the OrderDetails.aspx view. Here, we will elide discuss about the OrderDetails.aspx view since it is pretty simple.

    Concerning the rest user management related views, since they are all straightforward to follow, we, also, are not going to delve into them. Readers can continue to better them based upon their respective facts.

    Summary

    In this article, we have constructed a simple front-end of an online book store system with the help of Microsoft ASP.NET MVC framework. As you may have noticed, there are many aspects still needed to be enhanced or added, such as the AJAX-styled updating, the more secure user info management, more practical support to introduce online payment, more auxiliary modules to generate a practical application, etc. Anyway, if there are any questions in the basic modules introduced in this article, welcome to contact me by leaving a note here or email me.

    Build a Front End of an E-commerce System Using ASP.NET MVC Framework Series

  • Part 1 Build a Front End of an E-commerce System Using ASP.NET MVC Framework Part 1
  • Part 2 Build a Front End of an E-commerce System Using ASP.NET MVC Framework Part 2
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Xianzhong Zhu

    I'm a college teacher and also a freelance developer and writer from WeiFang China, with more than fourteen years of experience in design, and development of various kinds of products and applications on Windows platform. My expertise is in Visual C++/Basic/C#, SQL Server 2000/2005/2008, PHP+MyS...

    This author has published 78 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    ASP.NET MVC Dynamic Model Binding
    Dynamic model binding enables a single action to handle multiple forms.
    Using HTML5 Web Storage in ASP.NET
    HTML5 Web Storage provides a streamlined data storage mechanism that allows developers to store data...
    Implementing Website Pinning in ASP.NET
    Learn to enable website pinning features of IE9 on Windows 7 for your ASP.NET websites.
    Building a YouTube-like Video Playing Site Using ASP.NET Techniques - Part 3
    In this final part of this series, we are going to discuss how to make the users play their selected...
    Running multiple websites in a single hosting space
    Develop a solution that supports multiple websites in a single hosting space and database.

    You might also be interested in the following related blog posts


    You should NOT use ASP.NET MVC if. . . read more
    WSE, DIME; WCF, MTOM; OH My! read more
    Silverlight SVC Web Service problems on IIS read more
    Is ASP.NET MVC a half-baked solution? read more
    ASP.NET MVC Release Candidate 2 read more
    SQL 2008 CLR Triggers, use a .NET class library in SQL using WPF read more
    Programmatically generating SQL(DDL) from M read more
    Open SQL Port for specific IP by ASP.NET Website read more
    Exposing Custom WCF Headers through WCF Behaviors read more
    UppercuT - Automated Builds - Custom Tasks read more
    Top
     
     
     

    Discussion


    Subject Author Date
    placeholder MVC practices are not recommended Imran Rashid 12/16/2009 1:21 AM
    RE: MVC practices are not recommended Jamie Jones 12/16/2009 4:09 AM
    placeholder GetOrderDetails Helper Function Wissam Bishouty 12/16/2009 2:27 AM
    can not restore booksh.bak to sql2005 Asp Fun 12/16/2009 3:38 PM
    placeholder RE: can not restore booksh.bak to sql2005 Sonu Kapoor 12/19/2009 5:32 PM
    About "cannot restore booksh.bak to sql2005" (1) Xianzhong Zhu 12/16/2009 5:57 PM
    placeholder RE: MVC practices are not recommended Xianzhong Zhu 12/16/2009 6:08 PM
    About "cannot restore booksh.bak to sql2005" (2) Xianzhong Zhu 12/16/2009 6:14 PM
    placeholder Database Sonu Kapoor 12/16/2009 8:46 PM
    Need SPs Asp Fun 12/17/2009 4:53 PM
    placeholder bak file can not be restore in SQL 2008 express Asp Fun 12/17/2009 5:02 PM
    An error in ~\bookshop\we.config file Asp Fun 12/21/2009 9:45 AM
    placeholder RE: An error in ~ Sonu Kapoor 12/21/2009 2:18 PM

    Please login to rate or to leave a comment.