ASP. MVC5 (b): Controller, view and model

Source: Internet
Author: User
Tags button type actionlink

Objective

This post focuses on the three core elements of ASP: Controller, view and model, and the following mind map describes the main content of this article.


Introduction to Controller Controller

Before introducing the controller, let's briefly describe how MVC works: The URL tells the routing mechanism which controller to use, which method (Action) is called in the controller, and provides the required parameters for the method. The controller responds to the user's input, modifies the model in response, and decides which view to use and renders the view.
Note: The MVC pattern provides the result of a method call, rather than a dynamically generated page.

以上内容对于初学者来说可能不太理解,不过没关系,经过后面的学习,待我们对MVC的整体架构有了一定的认识,再返回头来看这部分内容,便很好理解了。

The controller is one of the three core elements in the MVC pattern, which is responsible for the input of the corresponding user, the processing of the input data, and the provision of the related view output data.

Controller Basics

First, let's take a look at a few of the controller classes that are included by default in the new project created by the ASP. NET MVC5 (a): ASP. Myfirstmvcproject:

    1. HomeController: Responsible for home page, about page, and contact page in the root directory of the website.
    2. AccountController: Responds to account-related requests, such as login and registration.
    3. Managecontroller: Responds to related pages that enable external service authentication.

Expand the Controller directory for the Myfirstmvcproject project, open the HomeController.cs file, and the code is as follows.

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MyFirstMvcProject.Controllers{    public class HomeController : Controller    {        public ActionResult Index()        {            return View();        }        public ActionResult About()        {            ViewBag.Message = "Your application description page.";            return View();        }        public ActionResult Contact()        {            ViewBag.Message = "Your contact page.";            return View();        }    }}

This is a very simple controller class that inherits from the controllers base class. The index method is responsible for determining which events are triggered when browsing the homepage of a website.

Creation of the Controller

To create a new controller, proceed as follows:

    1. Right-click the Controllers folder under Solution Eplorer, select add| Controller options.
    2. Select the MVC 5 controller-empty template and click the Add button.
    3. Name the controller Firstcontroller and click the Add button.

At this point, a controller named Firstcontroller has been created, and the Controller class already contains an index method, which we modify slightly (the return type is modified to a string type, and the return value is modified to this is my first Controller! ), the code is as follows:

    public string Index()    {        return "This is my first controller !";    }

Start the project, modify the URL to browse to/first/index, and then return the string for the response, such as.

The previous example returns a string constant, and the next step is to perform the action dynamically by responding to the parameters passed in by the URL. Modify the index method as follows:

    public string Index(string message)    {        return "This is my first controller ! The message is ‘" + message + "‘";    }

Start the project, modify the URL to browse to the/first/index?message=i ' m message.


The following conclusions can be drawn from the above demonstration:

    1. The way to determine whether a class is a controller is to see if the class inherits from System.Web.Mvc.Controller.
    2. You do not need to make additional settings, directly modify the URL browse to First/index can execute the index method in the first class, this is the operation of the route.

Introduction to view View

The purpose of a view is to provide a visual user interface to the user. When the controller executes the appropriate logic for the requested URL, it delegates the information (model) that will be displayed to the view. This process is divided into two operations, examining model objects and converting content to HTML format.

View Conventions

View Conventions: Under the View folder with the same name as the controller, each action method has a view file with the same name corresponding to it, which provides the basis for the view to associate with the action method.
Note: The above conventions can be overridden if you want the action method to render a different view, just give it a different view name, and when you use this syntax, you must provide the extension of the view file. We add the contact method to the Firstcontroller to render it under the home page.

    public ActionResult Contact()    {        return View("~/Views/Home/Contact.cshtml");    }

Starting the example, locating the URL to/first/contact, you can see that the rendered page is the contact view under home.

View Creation

The simplest way to create a view is to find the location under the Views folder that corresponds to the action, right-click add| View. However, Visual Studio provides a more convenient way to create a view by right-clicking on the controller's method and selecting the AddView key.

Strongly typed views

In MVC, the data transfer between the controller and the view can use ViewBag, ViewData, as shown in the following example:
Suppose you now need to write a view that shows all the user information, first, create a UserInfo class under the Models folder.

namespace MyFirstMvcProject.Models{    public class UserInfo    {        public int UserId { get; set; }        public string UserName { get; set; }        public string RegisterDate { get; set; }    }}

Under the Firstcontroller class, add the list method:

    public ActionResult List()    {        var userInfo = new List<UserInfo>()        {            new UserInfo {UserId = 1,UserName = "Aaron",RegisterDate = "2015-08-08" },            new UserInfo {UserId = 2,UserName = "Bob",RegisterDate = "2010-03-23" },            new UserInfo {UserId = 3,UserName = "Hunter",RegisterDate = "2014-09-12" }        };        ViewBag.UserInfo = userInfo;        return View();    }

Create a view, iterate over the view, and display user information:

<table class="table">@foreach (var item in ViewBag.UserInfo) {    <tr>        <td>            @item.UserId        </td>        <td>            @item.UserName        </td>        <td>           @item.RegisterDate        </td>    </tr>}</table>

Run the program as follows:


ViewBag: When passing small amounts of data to a view, it is easy to use viewbag, which becomes less convenient when you need to pass the actual objects, mainly in the inability to use IntelliSense, get strong typing, and compile-time checks. In this case, you can use the strongly typed view.
To modify the list method under Firstcontroller:

    public ActionResult List()    {        var userInfo = new List<UserInfo>()        {            new UserInfo {UserId = 1,UserName = "Aaron",RegisterDate = "2015-08-08" },            new UserInfo {UserId = 2,UserName = "Bob",RegisterDate = "2010-03-23" },            new UserInfo {UserId = 3,UserName = "Hunter",RegisterDate = "2014-09-12" }        };        return View(userInfo);    }

After the project is recompiled, the view is modified to find that IntelliSense is already available.


Run the program as follows:


Supplement: The difference between ViewBag and ViewData

    1. ViewBag is an object of type dynamic, and ViewData is a dictionary-type object.
    2. ViewBag can be used only if the keyword is a valid C # identifier, for example: viewdata["User Name", with spaces in the keyword, which cannot be compiled if ViewBag is used.
    3. ViewBag dynamic values cannot be passed to extension methods by parameters. For example: @Html. TextBox ("name", Viewbag.username) cannot be compiled, you can use viewdata["UserName"], or @Html. TextBox ("Name", (String) Viewbag.username).

Razor View Engine

Razor concept: Razor is a clean, lightweight, simple view engine that does not contain the syntax of the original Web Forms view engine and minimizes syntax and extra characters. Razor enables the transition between code and markup to be as smooth as possible by understanding the structure of the tag.
The core conversion character in Razor is the @ symbol, which is used to make the token-code conversion character. As in the example in the previous section, the Razor view engine can automatically identify <td> tags and item based on the @ symbol. UserID code.

    <td>       @item.UserId    </td>

The Razor view engine supports code blocks in addition to code expressions.

@foreach (var item in Model) {    <tr>        <td>           @item.UserId        </td>        <td>           @item.UserName        </td>        <td>          @item.RegisterDate        </td>    </tr>}

Layout

The use of layouts helps to maintain a consistent appearance across multiple views in your application in the same way as template pages in Web Forms. The following is a partial code for the default layout of the ASP. NET MVC5 New Project (located at views/shared/_layout.cshtml).

<body> <div class= "NavBar navbar-inverse navbar-fixed-top" > <div class= "Container" > <div class= "Navbar-header" > <button type= "button" class= "Navbar-toggle" data-toggle= "Collapse" da  Ta-target= ". Navbar-collapse" > <span class= "Icon-bar" ></span> <span class= "Icon-bar" ></span> <span class= "Icon-bar" ></span> </butto N> @Html. ActionLink ("Application Name", "Index", "Home", new {area = ""}, new {@class = "Navbar-brand "}) </div> <div class=" Navbar-collapse collapse "> <ul class=" Nav Navb Ar-nav "> <li> @Html. ActionLink (" Home "," Index "," Home ") </li> <li&gt  , @Html. ActionLink ("About", "about", "Home") </li> <li> @Html actionlink (' contact ', ' contact ',     "Home") </li>           </ul> @Html. Partial ("_loginpartial") </div> </div> </d            iv> <div class= "Container body-content" > @RenderBody () 

The @RenderBody in the view is the equivalent of a placeholder that marks where the view using this layout will render them.
When creating a default ASP. NET MVC project, a _viewstart.cshtml file is automatically added to the Views directory, which runs before any view, and if a set of views have common settings, we can Unified settings in the viewstart.cshtml.

Model

In this section, we will describe how to use entityframework to manipulate the model using a simple example.

Modeling Product Products

Add a new product class to the Model folder, right-click the Models folder and select Add| class, name the new class product, and add the properties of the response:

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace MyFirstMvcProject.Models{    public class Product    {        //产品编号        public int Id { get; set; }        //产品名称        public string ProductName { get; set; }        //产品描述        public string Description { get; set; }        //产品价格        public decimal Price { get; set; }    }}
Building Scaffolding for Product manager

The ASP. NET MVC5 contains various scaffolding templates, and the code generation of different templates is different. First, introduce some of the commonly used scaffolding templates in ASP. MVC5:

    1. MVC 5 Controller-empty:
      Add a controller class with an index operation to the Controller folder, and there is no code inside it that returns a default Viewresult instance.
    2. MVC 5 Controller with Read/write Actions:
      Add a controller to the project with the index, Details, Create, edit, and delete operations.
    3. MVC 5 Controller with views,using Entity Framework:
      Not only does it generate a controller with a full set of index, Details, Create, edit, and delete operations, but it also generates code that interacts with the database.

To create a controller for product products using scaffolding, proceed as follows:

    1. Right-click Controller folder, select Add| Controller.
    2. In the pop-up add scaffold Select MVC 5 Controller with views,using Entity Framework, click the Add button.
    3. In the Add Controllers dialog box, modify the controller name to ProductsController.
    4. Click the + button on the right side of the data context class to modify the database context name to Productstoredb and click the Add button.
    5. Once the confirmation is complete, go back to the Add Controller dialog box and click Add for the product class ProductsController and related views.

使用基架为模型创建控制器时,注意添加模型类后要重新编译该项目,否则在创建时Visual Studio可能会抛出异常

After the creation is complete, modify the database connection string in the Web. config file to connect to the database that you want to connect to (in this case, the SQL Server database connected to this computer)

Run the program and browse the URL to/products/index because no products have been added at this time, so there is no data in the list.

Click the Create new link, enter ProductName, Description, Price in the Add page, click Create, return to the/products/index page, and the data is added successfully.

Initialization and seeding of databases

The simplest way to ensure that the database is synchronized with the model changes is to allow the Entity Framework to recreate an existing database. You can modify the Global.asax file to invoke the static method Setinitializer in the database class of EF (located in namespace System.Data.Entity). Tells EF to re-create the database when the application starts or to rebuild the database (Dropcreatedatabasealways and dropcreatedatabaseifmodelchanges) only when the model changes are detected.

    protected void Application_Start()    {        //启动应用程序时重新创建数据库        Database.SetInitializer(new DropCreateDatabaseAlways<ProductStoreDB>());        AreaRegistration.RegisterAllAreas();        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);        RouteConfig.RegisterRoutes(RouteTable.Routes);        BundleConfig.RegisterBundles(BundleTable.Bundles);    }

In the actual development of the project, we always want to have some data in the database to be used for testing in development. The following describes the seeding database (seeding) to do this, creating a derived class of the Dropcreatedatabasealways class under the Models folder, overriding the seed method in it, and creating some initial data for the application.

public class ProductStoreDbInitializer : DropCreateDatabaseAlways<ProductStoreDB>{    protected override void Seed(ProductStoreDB context)    {        context.Products.Add(new Product        {            ProductName = "Apple Pencil",            Description = "iPad Pro - Apple Pencil - Apple",            Price = 99m        });        base.Seed(context);    }}

Register this initializer in the application startup code section as follows:

protected void Application_Start()    {        //启动应用程序时重新创建数据库,并播种数据库        Database.SetInitializer(new ProductStoreDbInitializer());        AreaRegistration.RegisterAllAreas();        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);        RouteConfig.RegisterRoutes(RouteTable.Routes);        BundleConfig.RegisterBundles(BundleTable.Bundles);    }

Restart and run the application, navigate to/products/index in the browser, and there is no need to enter data to be available.

ASP. MVC5 (b): Controller, view and model

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.