ASP. net mvc 4.0 learning 3-Model, mvc3-model

Source: Internet
Author: User
Tags asp net

ASP. net mvc 4.0 learning 3-Model, mvc3-model

The Model compute operator retrieves the data in the data volume and processes the data in the data volume.

All tasks related to data processing in MVC are completed by the Model. The Model determines the amount of data stored in the Model, and the Controller and View both obtain the Model, the operation for adding and modifying data volumes.

The Model does not need to depend on the Controller or View. Therefore, the architecture of the Model is very high. We can create a modeling case for the Model.

1. Add the actual data volume Model to the Model.

Add a new DataBase: message to the DataBase and add Table: MessageBoard.

USE [message] GO/****** Object: Table [dbo]. [MessageBoard] Script Date: 08/25/2014 09:42:13 *****/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ongocreate table [dbo]. [MessageBoard] ([ID] [int] IDENTITY (1, 1) not null, [msg_name] [nvarchar] (20) not null, [msg_Content] [nvarchar] (max) not null, CONSTRAINT [PK_MessageBoard] primary key clustered ([ID] ASC) WITH (PAD_INDEX = OFF, expiration = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]View Code

Create an MVC case and add a new ADO. NET real data model from the dataset:

 

2. Add the Service class to implement the CUDR of MessageBoard

Shortcut: Ctrl + M, O Ctrl + M, L Ctrl + K, S add external token

Create a Service file catalog and add a class:

In this example, we can check the MessageBoard additions and deletions:

Using System; using System. collections. generic; using System. linq; using System. web; using MvcApplication2.Models; namespace MvcApplication2.Service {public class messageDBService {// real instance data size MessageEntities database = new MessageEntities (); # region Create Function // Create method, parameters are name and content public void Create (string name, string content) {// an example is provided to define MessageBoard NewMsg = new MessageBoard (); NewMsg. Msg_name = name; NewMsg. msg_Content = content; // Add the real object to the database. messageBoards. add (NewMsg); // save database. saveChanges ();} // The Create method retries. The value is the public void Create (MessageBoard NewMsg) of MessageBoard type) {// Add the real object to the database. messageBoards. add (NewMsg); // save database. saveChanges () ;}# endregion # region Update Function // update. The number of updated IDs, names, and content public bool Update (int id, str Ing name, string content) {// check whether MessageBoard msg = database. MessageBoards. Find (id); if (msg! = Null) {msg. msg_name = name; msg. msg_Content = content; database. saveChanges (); return true;} else {return false;} // update. The maximum value is MessageBoard public bool Update (MessageBoard msgUpd) {// check whether the id corresponds to the MessageBoard msg = database. messageBoards. find (msgUpd. ID); if (msg! = Null) {msg. msg_name = msgUpd. msg_name; msg. msg_Content = msgUpd. msg_Content; database. saveChanges (); return true;} else {return false ;}# endregion # region Delete Function public bool Delete (int id) {MessageBoard msgDel = database. messageBoards. find (id); if (msgDel! = Null) {// Delete database. messageBoards. remove (msgDel); return true;} else {return false ;}# endregion # region Query Funcion // return all messages public List <MessageBoard> GetList () {List <MessageBoard> msgList = database. messageBoards. toList (); return msgList;} // a message indicating public MessageBoard getMessage (int id) {MessageBoard msg = database. messageBoards. find (id); return msg ;}# endregion }}View Code

We have seen the role of the Model above: Pulling data from the data base by using the Entity, and adding processing of the corresponding data through the new type.

3. Relationship between Model-Controller-View

1. Added messageController to Controller.

2. added the preview file for ViewModel and added the IndexViewModel. cs file.

3. After Ctrl + Shit + B re-constructs the solution, add View to the right vertex Index () in messageController. We will select "IndexViewModel ".

4, so the relationship between the M-V-C came out: M (indexViewModel)-V (index. cshtml)-C (messageController)

4. ViewMode

The ViewModel is literally a Model used for the View.

The reference at the top of the View plane is as follows, and only one Model can be referenced. However, the attention of the View plane usually uses the field attention in the multi-lateral Table.

Therefore, we have created a View-oriented Model named ViewModel, which integrates all the necessary features for the View.

@model MvcApplication2.ViewModels.IndexViewModel

Content contained in ViewModel:

  • Define the atomicity of fields required by the View
  • Credit rules that contain privacy
  • There can be a combination of multiple different data types
  • Define the Interface format of a template (DisplayFor, EditFor, LabelFor)

Model Validate

In ViewModel, you can verify whether the value of a field obtained from the View has been compliant according to certain rules, for example, whether it is a correct response box address.

The following is a common license:

Using System; using System. collections. generic; using System. linq; using System. web; using System. componentModel; using System. componentModel. dataAnnotations; namespace MvcApplication2.ViewModels {public class IndexViewModel {// 1, and the Title response name in [DisplayName] View indicates that the Title response is required for the required response [DisplayName ("Required Course")] public string Title {get; set;} // 2, [Required] Name field cannot be blank, if it is null, the error message "ErrorMessage [Required (ErrorMessage =" Required Student name ")" is displayed.] Public string Name {get; set;} // 3, [StringLength] specifies the length of the string, and ErrorMessage indicates the length of a variable that does not conform to the length. [StringLength (10, errorMessage = "length must be between 2 and 10 characters", MinimumLength = 2)] public string Course {get; set ;}// 4, [Range] fixed numeric value limit [Range (0,100, ErrorMessage = "the Score must be between 0 and")] public int Score {get; set ;} // 5. If [Compare] is the same as another field [Compare ("re_password", ErrorMessage = "two passwords are inconsistent")] public string password {get; Set;} public string re_password {get; set;} // 6, [RegularExpression] returns the signature of the more positive table [RegularExpression (@ "^ (\ d {3, 4 }-)? \ D {7, 8}) $ | (13 [0-9] {9} ", ErrorMessage =" Please confirm your phone number ")] // :( ^ (\ d {3, 4 }-)? \ D {7, 8}) $ | (13 [0-9] {9}) public string Phone {get; set;} // 7, [EmailAddress] Email format certificate [EmailAddress (ErrorMessage = "please fill in the correct Email format")] public string StuMail {get; set;} // 8, [Url] [Url (ErrorMessage = "")] public string url {get; set ;}// [FileExtensions], preset format: .png,.jpg, .htm, .gif [FileExtensions (ErrorMessage = "upper limit file Format: upper limit")] public string file {get; set ;} // [CreditCard] [CreditCard (ErrorMessage = "")] public string creditCard {get; set ;} // query [DataType (DataType. date)] public DateTime date {get; set ;}}}View Code

 

 

 

 


How to further learn about aspnet (MVC)

You are a newbie to learn. NET
Learn MVC again
If you are a newbie to learn. NET and a newbie to learn mvc, it may be different.
If you want to learn. Net to the framework and design mode stage
We recommend that you learn MVC
If not. Net

What are the differences between asp net 40 and asp net 35 MVC?

In 4.0, you can use more new features,

Some extensions to 4.0 are provided in the source code of ASP. net mvc, Which is useless in 3.5.
For example, the optional parameter Helper, The ViewPage that supports dynamic: DynamicViewPage, and some new verification Datameta

These features are available in Microsoft. Web. Mvc. AspNet4.dll.

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.