ASP. net mvc part.1 (create a basic MVC application)

Source: Internet
Author: User
Tags naming convention
ArticleDirectory
    • Selection of MVC and web forms
    • Create a basic MVC application

MVC is based on ASP. NET, so all ASP. NET skills can be applied to MVC applications.Program. MVC is a framework that allows you to quickly build applications using ASP. NET knowledge. It is similar to web forms and dynamic data frameworks.

MVC represents the Model-View-Controller. They are the names of the three main components in the application development style.

    • A model represents a data model. It can perform CRUD (create, read, update, and delete) operations on persistent application data. Functional abstraction is a key part of MVC. A model is the only place in an application that interacts with data storage.
    • A view is the part presented to users. It is an ASP. NET. ASPX page.. The content of a page is usually closely related to the crud operations to be performed by the user. Therefore, the page usually contains the content of one or more data items, or has a tool to edit or delete data items.
    • The Controller is C # used as a bridge between views and models #CodeFile. The Controller receives the request from the client and selects the view to serve the request..

 

Selection of MVC and web forms

Compared with web forms, MVC has a series of advantages:

    • Separation of models, views, and controllers makes unit tests in various aspects of applications easier.
    • More control over MVC applications in terms of details
    • This avoids the transmission of a large amount of State data on the server and client, while web forms cause a lot of trouble on the Internet.

However, the web form framework is still a powerful platform. Its rich control libraries allow you to quickly create powerful applications. Web form programs are relatively easy to create and run, the skills required to create web applications are easily available on the market. Web forms will not disappear, and this technology will continue to develop and update.

Web forms can continue to guide LAN applications. However, the Internet-based ASP. NET application is gradually close to MVC, because MVC has better support for testing and stronger controllability.

Create a basic MVC application

First, create an ASP. NET MVC2 web application in.

The MVC model is especially suitable for unit testing, because the model, view, and controller can be tested separately..Therefore, when creating a project, you will be prompted whether to create a unit test project. Unit tests are not described here. You can search for related knowledge.

The name of the project directory corresponds to their functions. The content directory contains static items and slices of the application. The scripts directory stores JavaScript files. The MVC Project template creates jquery and files required for basic verification and Ajax features.

The controllers directory contains the control class, which must follow a specific structure, and Visual Studio can help you handle it.

The models directory contains the data model you want to use. You can have multiple data models. In this example, we use the Entity Framework to generate a model, which is located in the directory where the type definition and context-related classes are placed.

The views directory contains the. aspx file, which is used to present content to users. This directory also has a specific structure.

The structure of the MVC project has specific default specifications. You do not have to place items in the default directory, but you can use some convenient features built in MVC to do so.

 

1. Create a model

The model part of the MVC application can be anything that can operate the application data. Usually it will be a LINQ to SQL or an entity framework model. Emphasize the abstraction throughout MVC, and separate the model from other components so that you can change the model at minimal cost.For example, move data originally stored in text files to SQL Server. The models directory stores classes that contain data processing logic.

Here I use the northwind sample database to create an Entity Framework Model. Right-click the models directory, add a new project, and select ADO. NET Entity Data Model. Compile the project immediately after creating the data model, so that the model data type can be used when the controller is created, and intelligent prompts can help automatically display the class name.

 

2. Create a controller

The controller processes the request and determines which view will be returned to the client. Most requests come from the view.For example, the user may request the default page of the MVC application, and the Controller will provide a view that lists all records of a specific database table. The HTML generated by the view contains links, which generate further requests to the Controller. For example, a link requests a detailed view of a Specific Row.

The easiest way to create a controller is to right-click the controllers directory and select Add controller. You will be reminded to enter the Controller name, itFollow the naming conventions ending with controller.For example, the controller we want to create works with the products table of the northwind database, so we can name it productcontroller.The prompt box also contains a check box for creating activities for creation, update, deletion, and detailed scenarios. After this check box is selected, vs uses the correct naming convention to create a template method.After completion, a productcontroller. CS file will be created in the controllers directory. The following code starts with this file:

 using system; 
 using system. Collections. Generic; 
 using system. LINQ; 
 using system. Web; 
 using system. Web. MVC; 
 using basicmvcapplication. Models; 
 
 namespace basicmvcapplication. controllers 
{
 public class productcontroller: controller 
{
 // 
 // get:/product/
 
 Public actionresult index () 
{
 return view (); 
}
 
 // 
 // get:/product/details/5 
 
 Public actionresult details (int id) 
{
 return view (); 
}

The comments before each method explain the request format when the Controller method is called. For example, the index method is called when a user requests a URL/product /..

For our basic application, we hope this method will return all the items in the northwind Products table. That is to say, the responsibility of the index Controller method is to retrieve records from the products table and select a view for displaying the data. The following is a complete method:

Public actionresult index ()
{
Northwindentities DB = new northwindentities ();
VaR DATA = dB. Products;
Return view (data );
}

The view () method will be explained later. Now you only need to know That it selects the default view to display the index of the Products table.

 

3. Create an index View

When the view is called in the Controller Method index, a set of product instances is introduced. It is used to tell the MVC Framework to display data using the product-type index view. The problem is that this view does not exist.

To create this view,Right-click any code of the index Controller method and select add view.. You can see that the view name has been recommended through the Controller method name. Select the option to create a strong view and select basicmvcapplication from the list. models. product type. This will create a view that uses members of this data model type (if no type is available, compile and try again ).

Select "list" for the View content to select the view type to be created. Its options correspond to the template method created in the Controller class..After you click Add, vs creates the views/products directory and generates the View File index. aspx. You will see some new tags in this file. I will introduce them later.

 

4. Test (unfinished) Applications

Now we have a model, a partially encoded controller, and a view. This is enough to check whether the project works properly. The browser displays the default view of the program, which is created by the MVC template. The default view will be modified later. To connect to our controller, add/product to the URL of the browser. The URL format is as follows:

Http: // localhost: 7537/product

Each row is listed, and each row has corresponding edit, delete, and detailed links. At the bottom of the screen is the "Create a new project" link. However, an error occurs when you click any link. This is because we have not created a view for these links or implemented the associated Controller method.

 

5. Complete the controller and view

Now that we have a basic framework, we can implement the remaining controller methods and corresponding views. Complete code and detailed comments are shown in the Code as follows:

 
Using system;
 
Using system. Collections. Generic;
 
Using system. LINQ;
 
Using system. Web;
 
Using system. Web. MVC;
 
Using basicmvcapplication. models;
 
 
 
Namespace basicmvcapplication. Controllers
 
{
 
Public class productcontroller: Controller
 
{
 
//
 
// Get:/product/
 
 
Public actionresult index ()
 
{
 
Northwindentities DB = new northwindentities ();
 
VaR DATA = dB. Products;
 
Return view (data );
 
}
 
 
 
//
 
// Get:/product/details/5
 
 
 
Public actionresult details (int id)
 
{
 
Northwindentities DB = new northwindentities ();
 
VaR DATA = dB. Products. Where (E => E. productid = ID). Select (E => E). Single ();
 
Return view (data );
 
}
 
 
 
// The task of this create method is to create a new product instance and pass it to the view method.
// This create method is called when you click "Create Project" in the index view.
 
// Get:/product/create
 
 
 
Public actionresult create ()
 
{
 
Return view (New Products ());
 
}
 
 
 
// The following create method is called when the user fills in the details of the new product and submits the form.
 
// Modify its parameters to accept the products instance
 
// This is a convenient feature in MVC. The http post operation is converted to the Data Type processed by the Controller.
 
// Post:/product/create
 
 
 
[Httppost]
 
Public actionresult create (products prod)
 
{
 
Try
 
{
 
// Todo: Add update logic here
Northwindentities DB = new northwindentities ();
 
DB. addtoproducts (prod );
 
DB. savechanges ();
 
Return redirecttoaction ("Index ");
 
}
 
Catch
 
{
 
Return view ();
 
}
 
}
 
 
 
// Similar to the create method, the edit and delete functions are displayed in pairs and the operation modes are the same.
 
// Call a method when the user starts to edit or delete the database, and call another method when the operation is completed and the database is modified.
 
// Get:/product/edit/5
 
 
 
Public actionresult edit (int id)
 
{
 
Northwindentities DB = new northwindentities ();
VaR DATA = dB. Products. Where (E => E. productid = ID). Select (E => E). Single ();
 
Return view (data );
 
}
 
 
 
// In addition to the product ID edited by the user,
 
// Also input a formcollection containing the name/value pair that describes the product information
 
// Post:/product/edit/5
 
 
 
[Httppost]
 
Public actionresult edit (int id, formcollection collection)
 
{
 
Try
 
{
 
// Todo: Add update logic here
 
Northwindentities DB = new northwindentities ();
 
Products prod = dB. Products. Where (E => E. productid = ID). Select (E => E). Single ();
 
 
// This is a very useful and convenient method. It uses the fields submitted by the user to update the objects obtained from the model.
 
Updatemodel (prod );
 
DB. savechanges ();
 
 
 
Return redirecttoaction ("Index ");
 
}
 
Catch
 
{
 
Return view ();
 
}
 
}
 
 
 
//
 
// Get:/product/delete/5
 
 
 
Public actionresult Delete (int id)
 
{
 
Northwindentities DB = new northwindentities ();
VaR DATA = dB. Products. Where (E => E. productid = ID). Select (E => E). Single ();
 
Return view (data );
 
}
 
 
 
//
 
// Post:/product/delete/5
 
 
 
[Httppost]
 
Public actionresult Delete (int id, formcollection collection)
 
{
 
Try
 
{
 
// Todo: Add Delete logic here
 
Northwindentities DB = new northwindentities ();
 
VaR DATA = dB. Products. Where (E => E. productid = ID). Select (E => E). Single ();
 
DB. Products. deleteobject (data );
DB. savechanges ();
 
Return redirecttoaction ("Index ");
 
}
 
Catch
 
{
 
Return view ();
 
}
 
}
 
}
 
}

For each controller method, right-click the code declaration to add a view.You only need to add a View to the first method in each group.. Finally, there should be five views in the views/product directory: Create. aspx, delete. aspx, Edit. aspx, details. aspx, and index. aspx.

Now we have a complete but basic MVC application. All links and functions are also available.

 

6. Modify the site. Master File

The final task is to update the site. master file in the views/shared directory so that it does not reference the homecontroller automatically created by the vs MVC project. Modify the link of the first activity so that the last parameter is product:

<Li> <%: HTML. actionlink ("Homepage", "Index", "product") %> </LI>

Delete the second link (pointing to the about activity method), which is not implemented here.

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.