ASP. MVC4 Advanced Programming Learning Notes-model learning lesson four scaffolding and model binding 20171027

Source: Internet
Author: User
Tags actionlink

MVC model One, build scaffolding.

Scaffolding in MVC can provide the application with the boilerplate code needed to generate the curd various functions. When adding a controller, you can select the appropriate template and the entity object to generate the corresponding template code.

First define a model class as follows:

namespaceLYG. helloworld.models{ Public classAlbum { Public Virtual intalbumID {Get;Set; }  Public Virtual stringTitle {Get;Set; }  Public Virtual decimalPrice {Get;Set; }  Public VirtualArtist Artist {Get;Set; } }      Public classArtist { Public Virtual intArtistID {Get;Set; }  Public Virtual stringName {Get;Set; } }}
View Code

Then choose to add the controller, select the appropriate scaffolding, there are a lot of different scaffolding listed here.

Then click Next to select the appropriate model and data context as shown, then click Add button.

This will generate curd's various operating codes and view files generated at the same time, greatly simplifying the workload and increasing productivity. Here, because the new contact scaffolding is not clear about the advantages and disadvantages of various scaffolding, follow-up will be a separate learning comparison, select the appropriate scaffolding for their project.

Second, scaffolding and Entity Framework.

1, Code priority agreement;

Development makes it easier to generate data structures that need to be stored in a code way.

2, DbContext class;

When using code-first development methods, you need to derive a class from the DbContext class of EF to access the database. This class has one or more dbset<t> properties. Each t represents the object to be persisted. Such as:

 Public classMusicstoredb:dbcontext { PublicMusicstoredb ():Base("defaultconnection")        { }          PublicDbset<album> Albums {Get;Set; }  PublicDbset<artist> Artists {Get;Set; } The controller then accesses the database as follows:vardb =NewMusicstoredb (); varAllalbums = fromAlbuminchdb.albums byalbum. Title AscendingSelectalbum; returnView (Allalbums.tolist ());}
View Code

The last view reads the data:

@model Ienumerable<lyg. Helloworld.models.album>@{Viewbag.title="Index";} @Html. ActionLink ("Create New","Create")</p><tableclass="Table"> <tr> <th>@Html. Displaynamefor (Model=model. Title)</th> <th>@Html. Displaynamefor (Model=model. Price)</th> <th></th> </tr>@foreach (varIteminchModel) {    <tr> <td>@Html. Displayfor (ModelItem=item. Title)</td> <td>@Html. Displayfor (ModelItem=item. Price)</td> <td>@Html. ActionLink ("Edit","Edit",New{Id=item. albumID}) |@Html. ActionLink ("Details","Details",New{Id=item. albumID}) |@Html. ActionLink ("Delete","Delete",New{id=item. albumID})</td> </tr>} </table>
View Code

Third, initialize the database

The data structure is often changed during the development process, and if you want to regenerate the new data structure field, you need to initialize the database, you can add the following code in the Global.asax.cs file:

Database.setinitializer (new dropcreatedatabasealways<musicstoredb> ());

This will cause the data to be rebuilt each time the application is started, but there is a problem that some of the underlying data that is initialized will be emptied so that it is easy to test and requires database seeding. As shown in the following code:

 Public classMusicstoredbinitializer:dropcreatedatabasealways<musicstoredb>    {        protected Override voidSeed (Musicstoredb context) {CONTEXT.ARTISTS.ADD (NewArtist {name="Li Xiaowei"}); CONTEXT.ALBUMS.ADD (NewAlbum {title="Wang Feng 2018 concert", price=580, artist=NewArtist {Name ="Li Xiaowei" } }); Base.        Seed (context); }}
View Code

Add the following code to the Global.asax.cs:

Database.setinitializer (new Musicstoredbinitializer ());

Note Here I test results are performed to delete the database when the database is being used, and then delete the exception, not found the reason. This is the exception that is thrown by the program:Cannot drop database "Musicstoredb" because it is currently on use.

Iv. Model Binding

Previously, the common notation for ASP. WebForm was to get the transferred parameter value by request.form["Title". If there are too many types of form fields, the feeling becomes lengthy and generic. ASP. NET MVC can be named by the form element with the same name as the model entity, so that all the field types that are transferred come through an entity parameter.

1, the default model binding Defaultmodelbinder, the code is as follows:

[HttpPost] // Note that the parameter here is the value of the parameter that is passed through the property in album and the control that is named by the element in the view sheet.   public actionresult Edit (Album Album)        {            if  (modelstate.isvalid)            {                 = entitystate.modified;                Musicdb.savechanges ();                 return Redirecttoaction ("Index");            }             return View (album);        }
View Code

Note that this model binder binds all parameters in the album, which increases the risk of a "repeat commit" attack, and you can set one or two properties that are not set using the model binder, which you will learn in the following learning, which you need to keep in mind.

2, display model binding Updatemodel, if the model is invalid Updatemodel throws an exception, the code is as follows:

[HttpPost] PublicActionResult Edit () {varAlbum =NewAlbum ();//Note Declaring an instance            Try{Updatemodel (album);//Show Model BindingsMusicdb.entry (album). State=entitystate.modified;                Musicdb.savechanges (); returnRedirecttoaction ("Index"); }                      Catch{                            returnView (album);} }
View Code

3, display model binding TryUpdateModel, if the model is invalid Updatemodel will not throw an exception, but will return true or false to indicate whether the model is valid, the code is as follows:

[HttpPost] PublicActionResult Edit () {varAlbum =NewAlbum ();//Note Declaring an instanceIf (TryUpdateModel (album))//Show Model Bindings{musicdb.entry (album). State=entitystate.modified;                Musicdb.savechanges (); returnRedirecttoaction ("Index"); }                      Else{                            returnView (album);} }
View Code

The byproduct of model binding is the model state, so it can also be written like this:

[HttpPost] PublicActionResult Edit () {varAlbum =NewAlbum ();//Note Declaring an instanceTryUpdateModel (album) If (Modelstate.isvalid)//Show Model Bindings{musicdb.entry (album). State=entitystate.modified;                Musicdb.savechanges (); returnRedirecttoaction ("Index"); }                      Else{                            returnView (album);} }
View Code

The knowledge of the model is done, and the next step is to learn how the model state works with the HTML helper method, the MVC validation feature, and the model binding.

ASP. MVC4 Advanced Programming Learning Notes-model learning lesson four scaffolding and model binding 20171027

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.