ASP. NET MVC3 learning experience-views and Models

Source: Internet
Author: User

View
3.1 Role of views
The role of a view is to provide users with a user interface. After providing a reference to the model, the view converts the model into a format that is ready to be provided to the user.
In ASP. net mvc, this process consists of two parts:
Check the ViewDataDictionary submitted by the Controller (accessed through the ViewData attribute), and convert its content to HTML format.
From ASP. net mvc 3, View data can be accessed through the ViewBag attribute, which is dynamic and has simple syntax and can access the same data accessed through the ViewData attribute. ViewData is encapsulated, so you can use a syntax similar to the access attribute to retrieve the value in the dictionary, such:
ViewBag. Message is equivalent to ViewData ["Message"]
Differences between the two: 1. ViewBag only works when the keyword to be accessed is a valid C # identifier.
For example, if you store a value in ViewBag ["Key With Spaces"], you cannot use ViewBag to access and change the value.
2. The dynamic value cannot be passed to the extension method as a parameter, because the C # compiler must know the type of each parameter during compilation to select the correct extension method.
For example, @ Html. textBox ("name", ViewBag. name) will fail to compile, If You Want To compile through two methods 1. Use ViewData ["Name"], 2, (string) ViewBag. name
In a strong-type view, ViewDataDictionary has a strong-type model object rendered by a view. This model may represent the actual domain object. For convenience, this Model object can be referenced through the Model attribute of the view.
For example :@{
Layout = null;
}
<H1> @ ViewBag. Message Control Behavior in the controller:
Public ActionResult Sample (){
ViewBag. Message = "Hello World ";
Return View ("Sample ");
}
Note: This controller sets the ViewBag. Message attribute as a string and returns a view named Sample, which will display the value passed to the ViewBag. Message attribute.
3.2 specify a view
By default, the View () View returned by the Operation Method in the Controller removes the View with the same name as the Controller. If you need to specify a different View to the View ("OtherView ") specify the name of the returned view.
In some cases, you need to specify a view in a different directory structure ~ Symbol syntax to provide the complete path of the view, such:
Public ActionResult Index ()
{
ViewBag. Message = "Hello World ";
Return View ("~ /Views/Example/Index. cshtml ");
}
3.3 strong type view
For example, compile a view that displays the Album list. The implementation is as follows:
Public ActionResult List ()
{
Var ablums = new List <Album> ();
For (int I = 0; I <5; I ++)
{
Albums. Add (new Album {Title = "Olive" + I });
}
ViewBag. Albums = albums;
Return View (albums );
}
The view is shown as follows:
<Ul>
@ Foreach (var a in (ViewBag. Albums as IEnumerable <Album> ))
{
<Li> @ a. Title </li>
}
</Ul>
However, in a strongly typed view, you can achieve this:
Public ActionResult List ()
{
Var ablums = new List <Album> ();
For (int I = 0; I <5; I ++)
{
Albums. Add (new Album {Title = "Olive" + I });
}
Return View (albums );
}
View:
@ Model IEnumerable <MvcMusicStore. Models. Album>
<Ul>
@ Foreach (var p in Model)
{
<Li> @ p. Title </li>
}
</Ul>
3.4 view Model
A view usually needs to display data that is not directly mapped to a domain model. You can compile a custom view model class to achieve this.
3.5 Add a view
L Scaffold Template
① Empty creates an Empty view and uses the @ model syntax to specify the model type.
② Create a view with a form for creating a new model instance, and generate a tag and editor for each attribute of the model type.
③ Delete creates a view with a form for deleting an existing model instance, and displays a tag and the value of this attribute for each attribute of the model.
④ Details creates a view that displays the labels and values of each attribute of the model type.
⑤ Edit creates a view with a form for editing existing model instances. A tag and editor are generated for every attribute of the model type.
⑥ List create a form with model instances and generate a column for each attribute of the model type. Make sure that the operation method passes the IEnumerable <OliveType> type to the view, the view also contains links to operations for creating, editing, and deleting operations.
L Reference script libiaries: indicates whether the created view contains a file set pointing to Javascript. You need to select these items when creating the Create or Edit view, if you want to verify the client, you must also select these items.
3.6Razor view Engine
3.6.3 code expression
Example: @ {string root = "Olive ";}
<Span> @ root. Models </span>
The output result is <span> Olive. Models </span>.
However, an error is reported during actual operation, prompting that the string does not have the Models attribute. You can enclose the expression in parentheses to solve the problem:
<Span> @ (root). Models </span>
Example: <li> Item_@item.Length </li>
The expected output result is <li> Item_3 </li>.
But the actual output is <li> Item_@item.Length </li>
This is because Razor recognizes it as an email address,
We only need to add parentheses, such as: <li> Item _ @ (item. Length) </li>
In addition, if you want to output the @ number as follows, you can use two @ for escape.
3.6.4Html Encoding
In many cases, you need to use a view to display user input. However, there are potential cross-site scripting attacks, but the Razor expression uses HTML encoding by default.
As follows: @ {string message = "<scrui> alert ('live') </script> ";}
<Span> message </span>
This code will not pop up a prompt box, as shown below:
<Span> <script> alert ('live'); <script> </span>
If you want to display the HTML Tag, you need to return the instance of the System. Web. IHtmlString object. Razor does not encode it, or you can use Html. Row to display it.
@{
String message = "<scrui> alert ('live') </script> ";}
<Span> @ Html. Row (message) </span>
In this way, the pop-up box is displayed.
At the same time, when assigning user-supplied values to variables in Javascript, Javascript string encoding instead of HTML encoding is required, that is, the @ Ajax. JavaScriptStringEncode method is used to encode user input.
This effectively avoids cross-site scripting attacks, as shown below:
<Script type = "text/javascript">
$ (Function (){
Var message = 'Hello @ Ajax. JavaScriptStringEncode (ViewBag. UserName )';
$ ("# Message" ).html (message). show ('low ');
});
</Script>
3.6.5 Razor syntax example
1. Implicit code expression
<Sapn> @ model. Message </span>
In Razor, implicit expressions always use HTML encoding.
2. display code expressions
<Span> ISBN @ (isbn) </span>
3. No encoding code expression
Use the Html. Row Method to Determine whether the content is not encoded.
<Span> @ Html. Row (model. Message) </span>
4. Code Block
@{
Int x = 123;
String y = "because ";
}
5. Text and tag combination
@ Foreach (var item in items)
{<Span> Item @ item. Name. </span>}
6. Mixed code and plain text
@ If (show)
{
<Text> This is Olive </text>
}
Or
@ If (show)
{
@ This is Olive
}
3.6.6 Layout
The layout in ASP. net mvc 3 is equivalent to the master page in WebForm.
Some Code in the following layout page:
<Div id = "main-content"> @ RenderBody () </div>
The @ RenderBody () is equivalent to the placeholder in WebFrom.
Layout example:
@{
Layout = "~ </Views/Shared/Layout. cshtml ";
}
<Span> This is main content! </Span>
In addition, there may be multiple sections in the layout, as shown in the following code:
<Div id = "main-conten"> @ RenderBoday () </div>
<Footer> @ RenderSeciton ("Footer") </footer>
If no changes are made to the view page, an error is reported. You need to modify the view page as follows:
@{
Layout = "~ </Views/Shared/Layout. cshtml ";
}
<P> This is a main content! </P>
@ Section Footer {
This is the <strong> footer </strong>
}
@ Section syntax specifies content for a section defined in the layout. By default, the view must specify content for the section defined in the layout, but the RenderSection method has an overloaded version, you can specify unnecessary sections. It is optional to pass a false value for the required parameter to mark the Footer section, as shown below:
<Footer> @ RenderSection ("Footer", false) </footer>
You can also define the default content of some French fries that do not define the festival. The method is as follows:
<Footer>
@ If (IsSectionDefined ("Footer "))
{
RenderSection ("Footer ");
}
Else
{
<Span> This is the default footer. </span>
}
</Footer>
3.6.7 ViewStart
Create a default ASP. net mvc 3, _ ViewStart is automatically generated. the cshtml file points to a default layout. If a group of views have common settings, _ ViewStart. the cshtml file is useful, but if you need to select another Layout, you need to re-specify the Layout attribute of the view as follows:
@{
Layout = "~ /Views/Share/others. cshtml ";
}
3.7 specify a division View
In addition to the returned view, the operation method also uses the PartialView method to return the partial view in the form of PartialViewResult:
For example:
Public ActionResult Message ()
{
ViewBag. Message = "This is Olive ";
Retrun PartialView ();
}
If the layout is specified by the _ Viewstart. cshtml page, the layout cannot be rendered.
The branch view is mostly used for partial update in AJAX technology.
For example, use JQuery to load a partial view to call the current view using AJAX:
<Div id = "result> </div>
<Script type = "text/javascript">
$ (Function (){
$ ('# Result'). load ('/home/message ');
});
</Script>
3.8 view Engine
First, let's take a look at the lifecycle of ASP. net mvc 3,


The controller does not render the View itself. It only prepares for the summer vacation and returns a ViewResult instance to determine which View to display. The controller base class contains a simple method named View to return a ViewResult instance, the ViewResult in the background of the view engine is called to render the view in the current view engine.
Chapter 4 Model
This chapter describes the model objects that are sent to the database, executed for business computing, and rendered in the view. These tokens represent the domain of interest to the application. The model is to save, create, update, and delete objects.
4.2.1 concept of Base Frame
The basic framework of ASP. net mvc provides the required sample code for application creation, reading, updating, and deletion (CRUD. The Base Frame template detects the definition of the model class, and then generates a view of the controller and the controller control.
There are three templates available for ASP. NET MVC3:
L Empty Controller: This template adds a Controller with the specified name and derived from the Controller class to the Controller folder. This Controller only carries the Index operation, only one default ViewResult instance is returned internally, and no view is generated.
L Controller with Empty Read/Write Actions: This template adds an Index, Details, Create, Edit, and Delete operation Controller to the project, but you also need to add code for it, and create a view for it.
L Controller with Read/Write Actions and Views, Using Entity Framework: This template generates a complete set of Operation controllers with Index, Details, Create, Edit, and Delete operations, and all related Views, the code for interacting with the database is also generated. This template needs to specify the appropriate class model (the base frame detection detects all attributes of the selected model, and then creates the controller, view, database operation, and other code based on the information) and data context Object Name
4.2.2 Base Frame and Entity Framework
EF (Entity Framework) is an object-link ing Framework. It can save objects in relational databases, or retrieve. NET objects stored in relational databases using the LINQ query statement.
All the attributes of the model class we created earlier are virtual attributes, which means that these attributes are not mandatory, but they provide EF with a hook pointing to a pure C # class set, some features are enabled for EF. EF needs to know the time when the model attribute value is modified. At this moment, an UPDate statement is generated to make these changes consistent with the database.
L code priority
EF has conventions on foreign key relationships, database names, and so on. These conventions replace all mappings and configurations previously required for a relational object ing framework.
L DbContext
When using code precedence, you must use a class derived from the DbContext class of EF to access the database. This class can have more than one field of the DbSet <T> type. Each T of the DbSet <T> type represents an object to be permanently saved.
4.2.3 execute the base frame Template
1. Data Context
The class inherited from the DbContext class mentioned above is as follows:
[Csharp]
Public class MusicStoreDB: DbContext
{
/// <Summary>
/// Used to store objects of the Album type, which is equivalent to the Album table in the database
/// </Summary>
Public DbSet <Album> Albums
{
Get;
Set;
}
/// <Summary>
/// It is used to store objects of the Artist type, which is equivalent to the Artist in the database.
/// </Summary>
Public DbSet <Artist> Artists
{
Get;
Set;
}
/// <Summary>
/// It is used to store Genre objects, which is equivalent to the Genre table in the database.
/// </Summary>
Public DbSet <Genre> Genres
{
Get;
Set;
}
}
  

To access the database, you only need to instantiate the data context class.
2. Load related objects
① Pre-loading: Use the query statement to load all data as much as possible
② Delayed loading: load related data as needed
4.2.4 run the base frame code
1. Create a database using an object framework
EF Code gives priority to conventions rather than configurations. If you do not configure the ing from the model to the database table, EF will create a database mode using conventions. If you do not configure a specific database connection, EF creates a connection according to the Conventions.
EF is connected to the server. If the database cannot be found, a database is created. In this database, the ed1_adata table is EF used to ensure that model classes and database modes are synchronized. If you modify a model class, such as adding or deleting an attribute of the model class, EF will not re-create a database based on the model class, or throw an exception if it returns an error.
2. Use the database initialization Tool
An easy way to synchronize database and model changes is to allow the Entity Framework to recreate an existing database, informing EF to recreate the database every time the application restarts or detects model changes.
When you call the static SetInitializer method of the Database Class of EF, you need to pass an IDataBaseInitializer object to it. The framework contains two IDatabaseInitializer objects: DropCreateDatabaseAlways and DropCreateDatabaseIfModelChanges, both initiators need a generic class parameter, and this parameter must be a derived class of DbContext:
Example: Set an initiator each time you start a program
Add a code in the global. asax. cs internal Application_Star () method.
Database. SetInitializer (new DropCreateDatabaseAlways <MusicStoreDB> )());
3. Seeding Database
If you need some initial data when running the program, you can create the DropCreateDatabaseAlways class and override the Seed method.
As follows:
[Csharp]
Public class MusicStoreDbInitializer: DropCreateDatabaseAlways <MusicStoreDB>
{
/// <Summary>
/// Rewrite the Seed method to provide raw data for the program
/// </Summary>
/// <Param name = "context"> </param>
Protected override void Seed (MusicStoreDB context)
{
Context. Artists. Add (new Artist
{
Name = "Olive"
});
Context. Genres. Add (new Genre
{
Name = "Classic"
});
Context. Albums. Add (new Album
{
Artist = new Artist
{
Name = "Only"
},
Genre = new Genre
{
Name = "Pop"
},
Price = 9.99 m,
Title = "Only for you"
});
Base. Seed (context );
}
  

At this time, we also need to add the following code in the Application_Start event:
Database. SetInitializer (new MusicStoreDbInitializer ());
In general, we only need to do three steps:
1. Implementation Model
2. Build a base frame for controllers and views
3. Select the database initialization Policy
The base frame only provides a starting point for a specific part of the application, and can be modified based on your preferences.
4.3 edit an album
4.3.1 create and edit album Resources
In public ActionResult Edit (int id)
{
Album album = db. Albums. Find (id );
ViewBag. GenreId = new SelectList (db. Genres, "GenreId", "Name", album. GenreId );
ViewBag. ArtistId = new SelectList (db. Artists, "ArtistId", "Name", album. ArtistId );
Return View (album );
}
The highlighted code is used to build a list of schools and artists from the database. These lists are stored in ViewBag for filling in the DropDownList auxiliary method retrieval.
The SelectList class is used to represent the data required to build a drop-down table. The first parameter of the constructor specifies the items to be placed in the list, and the second parameter is an attribute name, this attribute contains the value used when you select a specified item. The third parameter is the end of the text to be displayed ("PoP") for each item, the fourth parameter contains the value of the selected item.
4.3.2 respond to POST requests during editing
This operation has an Album model object parameter and saves the parameter object to the database.
1. Edit happy path
Happy path is the code path that is executed when the model is in a valid state and the object can be saved to the database. The operation is performed through ModelState. isValid attribute to check the validity of the model object. If the model is in the valid state, then:
Db. Entry (album). state = EntityState. Modified;, the Code informs that the information already exists, and then update it.
2. Edit the sad path
The path used by the operation when the model is invalid. In the Sad path, the Controller operation needs to re-create the Edit view so that users can correct their own errors. Www.2cto.com
4.4 Model binding
4.4.1defamodelmodelbinder
When a parameter is included in an operation, the MVC runtime environment uses a model binder to construct this parameter. The default model binder is defamodelmodelbinder. For example, in the Album object scenario, the default binder checks the Album class and finds all Album attributes that can be bound. When the Model binder sees that Album has the Title attribute, it searches for the parameter "Title" in the request, the model binder uses the component request of the value provider to search for parameters in different regions. It can view route data, query strings, and form sets.
4.4.3 display model binding
When there are parameters in the operation, the model binder works implicitly. You can bind the call model displayed by the UpdateModel and TryUpdateModel methods in the Controller. If an error occurs during model binding or the model is invalid, UpdateModel throws an exception, but the TryUpdateModel method does not throw an exception, this method returns a Boolean value. "true" indicates that the model is successfully bound. "false" indicates that the model fails to be bound. Model binding generates a model State. Each value in the model is recorded in the model state. After binding, you can view the model status at any time to check whether the model is successfully bound.

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.