How to use Model in ASP. net mvc 3

Source: Internet
Author: User

Yesterday, my blog published a new article about how to use the Model in MVC. It is not a big technology, but a technical discussion ^

Original address: http://www.youguanbumen.net/Article.aspx? Id = 79

Original article:

I wrote an article ASP two days ago. net mvc 3 -- remote Model verification, mainly recorded ASP. net mvc 3 added the use of the RemoteAttribute class, thanks to this class, we can configure the client remote verification service for the attribute in the model, the article gives a simple entity class MyUser_Add, for example, the most common example is to verify the existence of a user name when registering a user. Finally, the user name is successfully verified with ajax salary increase. The code for giving the Model is as follows:

 
 
  1. /// <Summary>
  2. /// User-Added Operation Model
  3. /// </Summary>
  4. PublicclassMyUser_AddModel
  5. {
  6. # Region MyRegion
  7. /// <Summary>
  8. /// User Name
  9. /// </Summary>
  10. [DisplayName ("Logon account")]
  11. [Required (ErrorMessage = "user account cannot be blank")]
  12. [Remote ("CheckUserAccountExists", "Test", ErrorMessage = "user account already exists")]
  13. // Remotely verify Ajax)
  14. PublicstringUserAccount {get; set ;}
  15. }
  16.  
  17.  

After the article was posted to the blog site, a friend raised one point: "We can think that we can solve the duplicate problem during creation, but if it is an Update, I believe this statement should also report errors ". That is to say, if this Model is used for the Update operation, the method for verifying whether the user name exists is a little different from the Add operation because you need to exclude yourself, for example, the original user name is "user1" and then "user1". at this time, the criterion for determining whether a user name exists is "if the user name is 'user1' and the user ID number is not the user to be modified, the user cannot be used", the "Add" operation does not exist, so I can understand that both operations need to determine whether the user name exists, but different policies are used!

I just read the Demo that comes with ASP. NET MVC 3. It is the one generated after the MVC3.0 project is created --!), I want to write my opinion on "how Microsoft wants us to design the Model in MVC" and find that it seems to be somewhat related to this problem. My personal opinion is as follows:

First, let's take a look at AccountModels. cs under the Models directory in the Demo project. The following code is taken from two representative classes in this file, which are related to users. The source code is as follows:

 
 
  1. publicclassLogOnModel  
  2. {  
  3.     [Required]  
  4.     [Display(Name = "User name")]  
  5.     publicstringUserName { get; set; }  
  6.     [Required]  
  7.     [DataType(DataType.Password)]  
  8.     [Display(Name = "Password")]  
  9.     publicstringPassword { get; set; }  
  10.     [Display(Name = "Remember me?")]  
  11.     publicboolRememberMe { get; set; }  
  12. }  
  13. publicclassRegisterModel  
  14. {  
  15.     [Required]  
  16.     [Display(Name = "User name")]  
  17.     publicstringUserName { get; set; }  
  18.     [Required]  
  19.     [DataType(DataType.EmailAddress)]  
  20.     [Display(Name = "Email address")]  
  21.     publicstringEmail { get; set; }  
  22.     [Required]  
  23.     [ValidatePasswordLength]  
  24.     [DataType(DataType.Password)]  
  25.     [Display(Name = "Password")]  
  26.     publicstringPassword { get; set; }  
  27.     [DataType(DataType.Password)]  
  28.     [Display(Name = "Confirm password")]  
  29.     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]  
  30.     publicstringConfirmPassword { get; set; }  
  31. }  

Note that the class names of the above two classes are easy to understand. One is the "user) logon model" and the other is the "user) registration model ", interestingly, both classes use the UserName and Password attributes. The UserName authentication method is the same, while the Password is different. RegisterModel has a ValidatePasswordLengthAttribute feature-a custom verification feature. The two models correspond to different Action-views, so I understand that the Model exists for Actioin-View. For example, a page is used to display a form. This form will be submitted to an Action about the Post request. At this time, a Model corresponding to this form will be created, used to act as a media in views and actions. The so-called "object parameter passing ").

Return to the above question about checking whether the user name exists. Based on this idea, we can come up with a solution, that is, to create another new class called MyUser_UpdateModel user to modify the model.) We can get the following code:

 
 
  1. PublicclassMyUser_UpdateModel
  2. {
  3. /// <Summary>
  4. /// User Name
  5. /// </Summary>
  6. [DisplayName ("Logon account")]
  7. [Required (ErrorMessage = "user account cannot be blank")]
  8. [ValidateUserAccountAttribute] // custom Verification
  9. [Remote ("CheckUserAccountExistsForUpdate", "Test", ErrorMessage = "user account already exists")] // Remote Ajax verification)
  10. PublicstringUserAccount {get; set ;}
  11. }

Note that remote verification calls another Action. The code for this Action is as follows:

 
 
  1. /// <Summary>
  2. /// Used to verify whether the user account has an ActionUpdate Operation)
  3. /// </Summary>
  4. /// <Param name = "UserAccount"> User Account </param>
  5. /// <Returns> </returns>
  6. [HttpGet]
  7. Public ActionResult CheckUserAccountExistsForUpdate (string UserAccount)
  8. {
  9. VarMS = ModelState;
  10. String [] existsUsers = {"wodanwojun "};
  11. Bool exists = string. IsNullOrEmpty (existsUsers. FirstOrDefault (u => u. ToLower () = UserAccount. ToLower () = false;
  12. Return Json (! Exists, JsonRequestBehavior. AllowGet );
  13. }
  14.  
  15.  
  16.  
  17. Public class MyUser_UpdateModel
  18. {
  19. /// <Summary>
  20. /// User Name
  21. /// </Summary>
  22. [DisplayName ("Logon account")]
  23. [Required (ErrorMessage = "user account cannot be blank")]
  24. [ValidateUserAccountAttribute] // custom Verification
  25. [Remote ("CheckUserAccountExistsForUpdate", "Test", ErrorMessage = "user account already exists")] // Remote Ajax verification)
  26. Public string UserAccount {get; set ;}
  27. }

Assume that the user name to be modified is called "youguanbumen". During verification, if you enter the relevant department, you should not prompt "this account already exists" because it is his own, it's okay if you use this account ). I will not write the Controller code. I will get a Model named MyUser_UpdateModel class with the username "youguanbumen", and then pass the return View (object model) method to the View. Of course, view is strongly typed -- MyUser_UpdateModel class). The test result is as follows:

1. Enter "wodanwojun" as the user name. The user name cannot be used, just like the following one. For the reason, see the above Code!

2. Enter "youguanbumen" as the user name. No error message is found, as shown in the following figure. For the cause, see the code above and compare it with the code of another Action used for remote verification in the previous article!

To sum up, it seems that every article is not short, but there are very few things to talk about. Although I have little experience writing code, I still have some opinions on the code. Selecting a framework to develop a system means that you need to follow some agreed items during the development process, such as choosing WebForm to develop the system, accept the "event-related" and server-side controls as much as possible. If you select MVC, you must accept the fact that the C # code is embedded on the page, of course, this may not happen after some RIA frameworks are used, because everything on the page is basically returned asynchronously ). Especially when many people develop code, it is necessary for us to follow certain routines to write code. For example, in the above example, we may write Model, View, and Action, "if you follow this Action, there will be a Model to support it", then everyone can easily find the starting point of the Code, the person who writes the View knows how to declare that the page is of a strong type and will find the relevant Model.) The person who writes the Action knows what the model in return Viewobject model is, you also know what parameters are used to process Post actions. The Model writer needs to be familiar with the business, know which fields are required, and the fields have length restrictions, but he may not know how this Model will be presented!

ASP. the Model in net mvc is closely related to the business. What kind of Model will be generated when there is any business requirement, and corresponding actions will be taken out of it and corresponding views will be provided to display it. If you develop a system based on this idea, it is very likely that you will come up with a brief Development Process: Study the business --> convert to the corresponding Model, verify the attribute configuration of the Model based on business needs --> design a database table to store data, maybe xml is not necessarily) --> Design View to display it, design Action to process it .......

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.