Fifth, ASP. net mvc 3.0 [MVC practice project objective 1]

Source: Internet
Author: User

Some MVC-related things have been mentioned in the previous few articles. From this point on, we started to apply practical projects.

Practice a simple shopping process project!

First, create a blank solution, such as 1.

Figure 1. We expect to create three modules. One module contains our domain model, one module contains my MVC web application, and the other is a unit test module.

Our domain model is a class library project, followed by an ASP. net mvc3 web application (razor engine) project, and then add a test project to add a test project, such as 2.

Figure 2. when we create our domain class library project and test project (Class Library Project), Vs will automatically create a class1.cs file and unittest1.cs file, this is of little use to us and can be killed directly. What will we do next? 3.

Figure 3. The next step is to add a project reference. Packages (extension tools/third-party plug-ins) are required for the project. The third-party plug-ins used in our project are as follows:

Project Third plug-in name
Sportsstore. Domain Ninject
Sportsstore. UI Ninject
Sportsstore. Domain Moq
Sportsstore. UI Moq

In vs, you can use the following command to import a third-party plug-in package:

Install-package ninject-Project sportsstore. webui
Install-package ninject-Project sportsstore. Domain
Install-package Moq-Project sportsstore. webui
Install-package Moq-Project sportsstore. Domain

You can also right-click the relevant project and use the nuget package to manage the import one by one. The method is as good as you are!

The dependencies of our project are shown in the following table:

Project Dependent Project
Sportsstore. Domain None
Sportsstore. UI Sportsstore. Domain
Sportsstore. unittests

Sportsstore. Domain

Sportsstore. UI

Because we will use ninject to create our MVC application controller and process Di, we need to create a new class to change the configuration. Create a folder (named "Infrastructure") in the sportsstore. UI application and create a class named ninjectcontrollerfactory in the modified file. Its code is as follows:

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. MVC; using ninject; using system. web. routing; using Moq; using sportsstore. domain. abstract; using sportsstore. domain. entities; namespace sportsstore. webui. infrastructure {public class ninjectcontrollerfactory: defaultcontrollerfactory {private ikernel ninjectkernel; Public ninjectcontrollerfactory () {This . Ninjectkernel = new standardkernel (); addbindings ();} protected override icontroller getcontrollerinstance (requestcontext, type controllertype) {return controllertype = NULL? Null: (icontroller) ninjectkernel. Get (controllertype);} private void addbindings () {// bind additional data }}}

We need to register ninjectcontrollerfactory to the MVC Framework, so we also need to register it in global. asax. cs. The specific code is as follows:

Protected void application_start () {arearegistration. registerallareas (); registerglobalfilters (globalfilters. filters); registerroutes (routetable. routes); // register a routeControllerbuilder. Current. setcontrollerfactory (NewNinjectcontrollerfactory ());}

We can try to start and run my MVC web project. The result is as follows: 4.

Figure 4. If this error page is expected, the next task is to make it disappear!

Start with our domain model! Since we are working on a shopping process project, we certainly need products to shop, so create a folder (named "entities") in the domain model ") put the corresponding model in this folder to create a product class! The code of the product class is as follows:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace SportsStore.Domain.Entities{    public class Product : Object    {        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; }    }}

Next, create an abstract repository. We know that we can use some methods to interact with data. Here we use the repository mode, so we don't need to worry about how it is implemented, therefore, create a folder (named "abstract") in the domain model project to create an interface "iproductrepository" in this file. Its code is as follows:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using SportsStore.Domain.Entities;namespace SportsStore.Domain.Abstract{    public interface IProductRepository    {        IQueryable<Product> Products { get; }    }}

This interface uses this iqueryable <t> to get the product object. It does not say anything about how or where the data is stored or how it will be retrieved. A class that uses the iproductrepository interface to obtain the product object, but does not need to know where they are from or how they are delivered there, this is the most basic repository mode.

Then we use the simulated library, because we have defined an interface, so I will implement it and let it interact with the data. Let's simulate the IMPLEMENTATION OF THE iproductrepository interface. The Code is as follows:

Private void addbindings () {// bind additional data // simulate iproductrepository to implement mock <iproductrepository> mock = new mock <iproductrepository> (); mock. setup (H => H. products ). returns (new list <product> {New Product {name = "football", price = 25}, new product {name = "surf board", price = 179 }, new product {name = "running shoes", price = 95 }}. asqueryable (); this. ninjectkernel. bind <iproductrepository> (). toconstant (mock. object );}

The preparation work is almost the same. We need to show what we want to do. We need to first create the corresponding controller (named "productcontroller") to show our products "), the Code is as follows:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using SportsStore.Domain.Abstract;namespace SportsStore.WebUI.Controllers{    public class ProductController : Controller    {        private IProductRepository repository;        public ProductController(IProductRepository productReposittory)         {            this.repository = productReposittory;        }    }}

This is just an empty controller. We have created a constructor that receives parameters from iproductrepository, this facilitates ninject injection (constructor injection) during product Object Instantiation ). Then I need to return a view, So modify the productcontroller controller as follows:

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. MVC; using sportsstore. domain. abstract; namespace sportsstore. webui. controllers {public class productcontroller: controller {private iproductrepository repository; Public productcontroller (iproductrepository productrepository) {This. repository = productrepository;} // returns a public viewresult list () {return this. view (this. repository. products );}}}

Next, we need to add a view. We need to create a strong view, as shown in Figure 5.

Figure 5. of course, when we select the model class, the ienumerable <sportsstore cannot be found in the drop-down box. domain. entities. product>, because it does not contain enumerated domain model objects, we need to manually enter them.

Ienumerable <product> means that we can create a list. Now we can use the sharp razor engine to create this page. The code for the list. cshtml page is as follows:

@model IEnumerable<SportsStore.Domain.Entities.Product>@{    ViewBag.Title = "Product List";}@foreach (var Product in Model){    <div class="item">    

Note: @ Product. Price. tostring ("C"), tostring ("C") converts numbers to corresponding currencies based on your server.

Then we need to modify the default route as follows:

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. MVC; using system. web. routing; using sportsstore. webui. infrastructure; namespace sportsstore. webui {// Note: Instructions on enabling IIS6 or iis7 Classic mode, // visit the http://go.microsoft.com /? Linkid = 9394801 public class mvcapplication: system. web. httpapplication {public static void registerglobalfilters (globalfiltercollection filters) {filters. add (New handleerrorattribute ();} public static void registerroutes (routecollection routes) {routes. ignoreroute ("{resource }. axd/{* pathinfo }");Routes. maproute ("Default", // route name "{controller}/{action}/{ID}", // URL with parameters new {controller = "product ", action = "list", id = urlparameter. optional} // default value of the Parameter);} Protected void application_start () {arearegistration. registerallareas (); registerglobalfilters (globalfilters. filters); registerroutes (routetable. routes); // register the route controllerbuilder. current. setcontrollerfactory (New ninjectcontrollerfactory ());}}}

Note: The modification is the Controller name and action name marked as blue in the red section of the Code above.

Next, run our MVC web application. The running result is shown in 6.

Figure 6. We can see that the yellow pages have been wiped out. The project starts with something and continues to improve. If the description is incorrect, Please give some advice to the elders who pass by so that you can make better progress. Thank you!

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.