Talking about how to use model in ASP.net MVC 3

Source: Internet
Author: User
Tags add object net object model range return string

Yesterday blog sent a new article, tell me about how to use the model in MVC, not what the big technology, when it is a technical discussion ^ ^

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

Original:

I wrote an article two days ago. asp.net MVC 3--model Remote Authentication, which mainly records the use of the new Remoteattribute class in ASP.net mvc 3, which allows us to configure client-side remote checksums for properties in the model. In this paper, a simple entity class Myuser_add is given, and the most common example of verifying the existence of user names when registering a user is presented, and finally the function of using AJAX pay check is successfully implemented for user name. The code for model is as follows:

 
 
  1. <summary>
  2. Model of user Add action
  3. </summary>
  4. Publicclassmyuser_addmodel
  5. {
  6. #region Myregion
  7. <summary>
  8. User name
  9. </summary>
  10. [DisplayName ("Login account")]
  11. [Required (errormessage = "User account cannot be blank")]
  12. [Remote ("Checkuseraccountexists", "Test", errormessage = "user account already exists")]
  13. Remote Authentication (AJAX)
  14. Publicstringuseraccount {get; set;}
  15. }

After the article was sent to the blog Park, a friend put forward a point: "This we can think of the creation of the time to solve the problem of duplication, but if it is update, I believe that such statements should also be reported wrong." That is, if this model is used to do update operations, verify that the user name exists and add operation will be a little different, because to exclude themselves, such as the original user name "User1" modified also called "User1", at this time to determine whether the existence of the user name standard is " If a user name is ' user1 ' and the user ID number is not the current user to modify, then the user is unavailable (exists), and the add operation does not have "own", so I think it can be understood that two actions need to determine whether the user name exists, but use a different strategy!

Just before I saw ASP.net MVC 3 with the demo (that is, the creation of the MVC3.0 project after the build--! To write my own idea of how Microsoft wants us to design the model in MVC, it seems to be a bit of a connection to this issue, and here's my personal opinion:

First we look at the demo project in the models directory of the AccountModels.cs, the following code from this file in the two I think is very representative of the class, are related to the user, 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 above two classes of class names, we can easily read a "(user) login Model", one is "(user) registration model", the interesting place is that two classes are used username, password two properties, username authentication method is exactly the same, and password is different, Registermodel has a validatepasswordlengthattribute feature--a custom validation feature. The two models correspond to different action-view, so my understanding is that model is for Actioin-view. For example, there is a page that is used to display a form, this form is submitted to an action that describes the post request, and then a model corresponding to the form is created to act as a medium in view and action (the so-called "entity reference").

To get back to the question of whether or not the username exists, based on this idea, we can come up with a solution that is to create another new class called Myuser_updatemodel (the user modifies the model) and can draw the following code

 
  
  
  1. Publicclassmyuser_updatemodel
  2. {
  3. <summary>
  4. User name
  5. </summary>
  6. [DisplayName ("Login account")]
  7. [Required (errormessage = "User account cannot be blank")]
  8. [Validateuseraccountattribute]//custom validation
  9. [Remote ("Checkuseraccountexistsforupdate", "Test", errormessage = "user account already exists")]//long-range authentication (AJAX)
  10. Publicstringuseraccount {get; set;}
  11. }

Note that the remote authentication call is another action, and the code for this action is as follows:

 
 
  1. <summary>
  2. Action to verify the existence of a user account (used when the update operation)
  3. </summary>
  4. <param name= "UserAccount" > User account </param>
  5. <returns></returns>
  6. [HttpGet]
  7. Public ActionResult checkuseraccountexistsforupdate (string useraccount)
  8. {
  9. var ms = 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. public class Myuser_updatemodel
  15. {
  16. <summary>
  17. User name
  18. </summary>
  19. [DisplayName ("Login account")]
  20. [Required (errormessage = "User account cannot be blank")]
  21. [Validateuseraccountattribute]//custom validation
  22. [Remote ("Checkuseraccountexistsforupdate", "Test", errormessage = "user account already exists")]//long-range authentication (AJAX)
  23. public string UserAccount {get; set;}
  24. }

This assumes that the user to be modified is called "youguanbumen", so when the validation of the relevant department should not be prompted to "the account already exists" (because it is his own, use this account is no problem). Controller's code I do not write slightly, is basically to get a user named "Youguanbumen" Model--myuser_updatemodel class, and then through the return view (object model) method to throw to view (of course, View is a strongly typed--myuser_updatemodel Class), and the test results are screenshots as follows:

1, the input "Wodanwojun" as the user name, found that pass, just like the screenshot below this, the reason please see the above code!

2, enter "Youguanbumen" as the user name. Find no error prompts, like this screenshot below, for the reason see the above code, and against the other one in the previous article for remote verification of the action code!

Summary: Seems to write every article is not short but said things are very few, hehe, please do not mind ^_^. Although there is not much experience in writing code, individuals have some ideas about the code. Select a framework to develop a system, it means that in the process of development you need to follow some of the agreed things, such as selecting WebForm to develop the system, as much as possible to accept "event-appropriate" and server-side control; When you choose MVC, you'll accept the fact that C # code is embedded in the page, Of course, this may not happen if you use some RIA frameworks (because things on the page are basically asynchronous requests). Especially when many people are developing, it is necessary to follow certain routines to write code, such as the above example, perhaps when writing model, writing view, and writing action are three different people to complete, "If you follow this action will have a model to support it" the way to go, Everyone can easily find the point of the code, the person who writes the View knows how to declare the page as a strong type (he will find the relevant model), and the person who writes the action knows what model is in return View (object model), I also know what the parameters are for the action of the post, the person who writes the model needs to know a lot about the business, what fields are required, the length limit of those fields, and so on, but he may not know how to show this model.

asp.net MVC model is closely related to the business, what kind of business requirements will produce the model, and there will be a corresponding action to come out of it, have a corresponding view to show it. If the system is developed on the basis of this idea, it is possible to draw a brief development process: Research business--> into the corresponding model, according to the business needs of model properties configuration validation Characteristics--> Design a database table to store the data (perhaps XML is not necessarily)--> Design view to show it, design action to handle it ....

Original link: http://www.cnblogs.com/serafin/archive/2011/01/27/1945934.html

"Edit Recommendation"



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.