As part of the asp.net 3.5 Extensions preview, the Microsoft asp.net mvc framework has released the CTP version. Since then, the mvc framework has attracted the attention of many people in the industry and has been introduced on blogs and websites that various developers are interested in.
Brad Abrams, a member of Microsoft CLR and. NET Framework Team, released a very good example to show developers how to effectively use some of the latest tools in Microsoft mvc framework. This instance originated from Scott Guthrie's mvc instance. Scott put the content on his blog and demonstrated how the mvc framework was working in the initial form. Scott's instance uses a step-by-step method to write it into four parts:
Asp.net mvc framework Part 1)
Asp.net mvc framework Part 1): URL path selection
Asp.net mvc framework Part 1): transmits ViewData to the view from the Controller.
Asp.net mvc framework Part 1): Process Form editing and submission scenarios
The mvc Framework provides developers with sufficient flexibility to select View and model engines to meet their needs. In Scott's example, he used the LINQ to SQL model, but Brad decided to use the Entity Framework and use the Northwind database as the data source.
Developers can select a variety of model providers, such:
Nhib.pdf
LINQ to SQL
Entity Framework
In the future, we may also see other model providers:
SubSonic
LLBLGen Pro
LightSpeed
Or other known
The Brad method is to create an instance and guide developers to use asp.net mvc Application and Test to create a project. The developer needs to install the following content:
VS2008
Asp.net 3.5 Extensions
ADO. NET Entity Framework Tools Dec 07 Preview
Northwind sample database (Northwind. mdf)
ASP. net mvc instance Guide
This guide is widely used and has high learning value. You can learn about the functions of the mvc framework and how to link them together. Using mvc is different from Web Forms applications developed in the past, and even experienced asp.net Web Form developers need to get used to it gradually.
Getting started
Once asp.net 3.5 Extensions is installed, several project types are available, including asp.net mvc Web Application and Test. Asp.net mvc is designed as an easy-to-test framework, and Brad also uses the test function.
File/create a project-select asp.net mvc Web Application and Test
It creates a separate solution, including a Web application project, which can be used for unit testing. They are all pre-generated and contain some basic content you need to create.
ASP. net mvc instance: Create Routes
The Routing path selection in the mvc Framework is a very noteworthy function in the design. Developers can use it to determine how an application looks for a page. In a classic asp.net application, a page, such as home. aspx, always has a very clear path to access the page, usually like www.mywebsite.com/home.aspx. In comparison, Routing provides developers with more flexibility.
One of the powerful new features provided by asp.net mvc is its ability to customize URLs for accessing applications. Obviously, for the physical files on the disk and the URLs used to access the page function, the URL path selection feature isolates the association between the two. This is very important for the optimization of search engines and improving the universality of websites. For example, we do not need to access the address http: // localhost/Products/ItemDetails. aspx? Item = 42, but accessed through http: // localhost/Products/CodFishOil. Such a URL is more pleasing to the eye.
It creates a path table in the global. asax file of the mvc application. Fortunately, the default content in the template is sufficient for the application.
- RouteTable.Routes.Add(new Route
-
- {
-
- Url = "[controller]/[action]/[id]",
-
- Defaults = new { action = "Index", id = (string)null },
-
- RouteHandler = typeof(mvcRouteHandler)});
-
This Code provides the URLs format required for your website. The format is
Http: // localhost/Products/Details/CodFishOil
). Next, Action is the Details class method. Finally, the parameter passed to the details method is CodFishOil.
Of course, there may be other formats. You only need to modify the regular expression in the URL format string.
ASP. net mvc instance: Create Model)
Model is the heart of most web applications, and almost all data is stored in the model. The mvc framework allows developers to use any data source with almost no restrictions and easily switch between various data sources.
The model indicates the data you will use in the application. In this example, starting from the model, the core development of the application is a good choice.
Copy the Northwind. mdf file to the App_Data folder of mvcApplication. For SqlServer, Northwind may be the most common example database. You can download it from the official address. If you only need the original file, you can also obtain it from here.
Next, we need to create a LINQ Model Based on the northwind database to facilitate operations. You can use the nhib.pdf, LinqToSql, Entity Framework, or other. net orm technology. As long as it returns a. NET object, the asp.net mvc framework can operate on it. In this example, I use the Entity Framework.
Right-click the Models directory and choose add new item
In the dialog box, select ADO. NET Entity Data Model.
In the wizard, select "Generate from Database" and assign the default "Northwnd" connection string.
For the demo, we only need to use the Categories, Products, and Supplier data tables. Of course, you can also extend the demo to introduce more feature sets. However, do not select database views, stored procedures, and other data tables.
When you click Finish, VS will create a set of. NET classes, which are customized to create relevant content for accessing the database. We can also get a user-friendly designer to visually display the relationships between data.
Note that the default names given to these classes still use the database's plural nouns, but in our OR ing, they represent a single instance. To make the code readable, you should change all table names to accurate singular nouns: Category, Product, and Supplier. The Navigation attribute of Product also needs to be changed to the singular form, because there is only one Category for the Product) and the supplier Suppler ).
Next, we need to modify the namespace to make the code more accurate and intuitive ...... Right-click the design view and SET related properties. For example, set namespace to "NorthwindModels" and set the name of Entity Container to "NorthWindEntities"
Although we have not provided a complete example of the model, the provided content is sufficient to guide developers to complete the rest of the content ...... Let's jump to the next topic and take a look at the controller.
ASP. net mvc instance: Create a controller
The Controller is the brain of our applications. We can think of the Controller as the airport's air traffic controller, directing the plane's inbound and outbound directions. On the one hand, the Controller is responsible for obtaining data, and on the other hand, it is responsible for transferring data to the view.
Right-click the Controller directory and select "Add new Item ". In the dialog box, locate the mvc Controller and make sure that the assigned name ends with the Controller suffix. In our example, we will compile the ProductsController class.
Okay. Now we start with ProductsController. cs.
The Controller aims to prepare model objects for the view. We want to put the logic out of the view as much as possible, because it is difficult to test in the view. Therefore, in the controller, we access the model and obtain all created models. In this way, all views need to output some data.
First, we need to access the database.
1. Add the correct namespace, including Linq and references to our OR ing.
- using System.Linq;
-
- using NorthwindModel;
2. Next, we need to create an instance of the NorthwindEntities container class. Almost all actions access this class.
- public class ProductsController : Controller
-
- {
-
- NorthwindEntities Northwind = new NorthwindEntities();
Okay. Now we need to create the first action: display all categories. Remember, the Controller is responsible for preparing model objects for the view. When defining a new action, I like to write a comment to remind me of the URL to access this function.
The next thing to do is to access Categories from the model. You may need to add System. Collections. Generic reference to put the result in a Generic collection class, and then pass the result to the view named "Categories. This is a very simple example. We will add more complex logic here later.
- //URL: http://localhost/Products/Categories
-
- [ControllerAction]
-
- public void Categories()
-
- {
-
- List categories = Northwind.Categories.ToList();
-
- RenderView("Categories", categories);
-
- }
-
Next, we need to create the "Categories" view.
ASP. net mvc instance: Create View
For a view, the mvc framework gives developers and models almost the same flexibility. Developers can select a set of view engines and switch between them.
Right-click the Views folder and add the new directory "Products ". This allows us to clearly organize our views. Right-click the Views/Products folder and add a new mvc View Content Page. We will make full use of the Master Page, which is generated in the default project and can make the interface look more friendly.
Name the page Categories. aspx. The view name is very important. It must match the first parameter of the previously mentioned RenderView method.
By default, the project places the Master Page in Views/Shared/Site. Master.
ViewData is the content we want to pass from the Controller. To obtain a strong type access to it, we need to inform the view page of The expected type. This can be done by opening the codebehind file Categories. aspx. cs) and modifying the inherited type:
- public partial class Categories : ViewPage
-
- {
-
- }
-
To:
- public partial class Categories : ViewPage< List >
-
- {
-
- }
-
Then you can write clear, simple, and designed HTML. Note: Here I have made a loop on all the element items returned from ViewData, and then passed them as a linked list. I used the mvc auxiliary method Html. ActionLink to create a URL for the List action containing the corresponding product ID.
- < % foreach (var category in ViewData) { %>
-
- < %= Html.ActionLink(category.CategoryName, new { action="List", id=category.CategoryName }) %>
-
- < % } %>
-
ASP. net mvc instance: browse Products
Okay. Everything is ready and you can run it.
Press F5, and the Controller action: http: // localhost: 64701/products/Categories we just wrote will appear on the navigation bar.
An error occurs when you click any link because List action has not been written. This is what we will do next.
If you are used to "View in Browser" on the developed aspx page like me, you may see this error.
To reproduce this error, right-click Categories. aspx and select View in browser.
You will get an error. Why? Yes, please remember that in the mvc model, all the executions must go through the Controller, and the view itself cannot run. Tools will be improved in the future, but at least now, you can use F5 for default. aspx or run in browser. Of course, you should first make sure that you have compiled the solution.
List Action view now, let's go back to the content omitted previously: Add List action. What we need here is to find all products in the given Category. First, I need to get all products from the model, and then I must make sure that the Category reference has been loaded. By default, the Entity Framework provides an explicit Loading Model. Therefore, you must explicitly load all the tables you need. Finally, the view is displayed.
- //example URL:http://localhost:64701/products/List/Confections
-
- [ControllerAction]
-
- public void List(string id)
-
- {
-
- List products = Northwind.GetProductsByCategory(id);
-
- //prepare the view by explicitly loading the categories
-
- products.FindAll(p => p.Category == null).ForEach(p => p.CategoryReference.Load());
-
- RenderView("ListingByCategory", products);
-
- }
-
Note that I have called a custom METHOD OF THE NorthwindDataContext class. I personally prefer to encapsulate all the data access logic into this class. To define this method, right-click the Model, select CodeFile by adding new item, name it NorthwindDataContext. cs, and provide the following implementation.
- using System;
-
- using System.Collections.Generic;
-
- using System.Linq;
-
- namespace NorthwindModel
-
- {
-
- public partial class NorthwindEntities
-
- {
-
- }
-
- }
-
Now, you can easily add data access methods for this class. For example, we used the GetProductsByCategory () method.
- public List GetProductsByCategory(string category)
-
- {
-
- return Products.Where(p => p.Category.CategoryName == category).ToList();
-
- }
-
Next, we need to add the ListingByCategory view. Follow the same steps described above to add the ListingByCategory. aspx page under the Views/Products/directory.
This time, we should make ViewData a List type.
- public partial class ListingByCategory : ViewPage
-
- {
-
- }
-
Next we will implement the view. We just loop the View data and output it in the correct format.
- < %--Print out the catagory name--%>
-
- < % foreach (var product in ViewData) { %>
-
- < % if (product.Category.CategoryName != null) { %>
-
- < %=product.Category.CategoryName %>
-
- < % break; %> < %} //end if %>< %}//end foreach %>
-
- < % foreach (var product in ViewData) { %>
-
- < img alt="< %=product.ProductName %>" src="/Content/Images/< %=product.ProductID%>.jpg" />
-
- < %=product.ProductName %>
-
- Price: < %=String.Format("{0:C2}", product.UnitPrice)%>
-
- < % } %>
-
Once you add the/Content/Images directory to the instance project, the following page is displayed:
Brad's instance was written in C #, So Julie Lerman chose to create an example similar to Brad. She used VB. NET and AdventureWorksLT databases, and focus on more efficient Entity Framework queries. Julie pointed out a major difference between her implementation and Brad.
Note: the Entity Data Model is created from the AdventureWorksLT database.
In AW Translator's note: Short for AdventureWorksLT, the relationship between SalesOrderHeaders and Customer is the same as that between Products and Category in Northwind. Therefore, where he uses Products, I use SalesOrderHeaders; where he uses Categories, I use MERs.
To easily obtain data and pass it to the view, the key is to pass "one" object instead of the anonymous type) to the view. However, for each Order list with the Customer name) and the Details list with the data obtained from the Order and Customer), what we really need is an object graph.
- Encode and determine the data value in DataBound event processing
- Use ASP. NET 2.0 FormView to display data
- Format cells in ASP. NET DetailsView
- How to encode the data value in the DataBound event
- DetailsView display data by PAGE