This article provides some code design guidelines to help ASP. net mvc developers create reliable applications. Of course, you can select appropriate standards based on your actual applications. This article is translated by the EntLib.com team. You are welcome to share and exchange ideas on ASP. net mvc project development and design.
ModelSuggestions-Model Recommendations
A Model is an object that defines the business field. It should contain the business logic (how the object acts and is associated), the verification logic (the valid value of the verification object), and the data logic (how the data object is persisted ), and session logic (tracking user status ).
Create an independent ModelProject, in ASP. NET MVCReference Model in ProjectAssembly.
Place all business logic in Model.
If you place all business logic in the Model project, you can generate View and Controller based on actual business data. It has the following benefits:
- Reduce duplicate business logic.
- Reducing business logic in View makes View easy to understand.
- The test of business logic is only related to the Model.
For example, you need to display the user Name-display the Last Name first. The code in the View is as follows:
<% If (String. Compare (string) TempData ["displayLastNameFirst"], "on") = 0)
{%>
Welcome, <% = Model. lastName %>, <% = Model. firstName %>
<%}
Else
{%>
Welcome, <% = Model. firstName %> <% = Model. lastName %>
<% }%>
However, you need to repeat this logic in every place. If you place this business logic in the Model, you can add an attribute to the Model to encapsulate this logic.
Public string combinedName
{
Get
{
Return (displayLastNameFirst? LastName + "" + firstName: firstName + "" + lastName );
}
Private set
{
;
}
}
In this way, the view code can be greatly simplified:
<% Welcome, <% = Model. combinedName %>
Place all verification logic in ModelMedium
All input verification should be performed at the Model layer, including Client-side verification.
You can use ModelState to add a verification check. The Code is as follows:
If (String. IsNullOrEmpty (userName ))
{
ModelState. AddModelError ("username", Resources. SignUp. UserNameError );
}
However, a better way is to use System. ComponentModel. DataAnnotations and add attribute to the attributes of the Model class, as shown below:
Public class User
{
[Required (ErrorMessageResourceName = "nameRequired", ErrorMessageResourceType = typeof (Resources. User)]
Public String userName {get; set ;}
...
}
Define interfaces for data access
Interfaces are used to expose the data consumer class and enhance the loose coupling design of ASP. net mvc.
You can use Entity Framework or LINQ to SQL to create a category for the database. Both Entity Framework and LINQ to SQL support stored procedures.
Place all session logic in Model.
ViewSuggestions-View Recommendations
View is used to display Model data. The Controller selects View. The business logic is not a View, and the Model is responsible for the business logic. View is very flexible. For example, the View of the Model can be displayed in HTML, and the same Model can also be displayed in XML View.
Set HTMLPlaced in ViewAnd Partial ViewInMedium)
The default ASP. NET View engine provides the following View files: HTML View (. aspx), Partial HTML View (. ascx), and Master page (. master)
The following view demonstrates the call to the partial view:
<% @ Page Title = "" Language = "C #" MasterPageFile = "~ /Views/Shared/Site. Master "Inherits =" System. Web. Mvc. ViewPage "%>
...
Below is a list of items submitted by <B>
<% = Html. Encode (ViewData ["name"]) %> </B>.
<P>
...
<Div id = "items">
<% Html. RenderPartial ("ItemsByName"); %>
</Div>
</Asp: content>
Partial view (ItemsByName. ascx) is as follows:
<% @ Control Language = "C #" %>
...
<% Foreach (Seller. Controllers. Items item in (IEnumerable) ViewData. Model)
{%>
<Tr>
<Td>
<% = Html. Encode (item. title) %>
</Td>
<Td>
<% = Html. Encode (item. price) %>
</Td>
</Tr>
<% }%>
</Table>
<% }%>
Partial View is a powerful extension and reuse mechanism. You can include the same View in different places without having to write repeated code.
In ViewUsing ViewDataAccess Data
ASP. NET provides the following mechanism to access data in the View template:
ViewData. Model object-in the action Method of the Controller, input a Model object (return View (myModelObject) in the return statement )).
ViewData Dictionary-store data in the action method (ViewData ["key"] = value), and then the dictionary with the same method in the View.
If possible, it should be a ViewData Model instead of ViewData to access data, because the Model provides type security. In addition, you should use the data access mechanism in the View template instead of the Request/Session for access.
To display multiple attributes of an object, you can use ViewData. Model and create a strong View. For the seller details page, the seller class has attributes such as name, phone, address, and email. Before presenting the View, you can assign a value to the seller object instance for ViewData. Model in the Controller. However, the ViewData dictionary is generally used for scattered data, such as page #, user name, and current time.
When using Model binding (Model bingding) To avoid.
Access the database in the Controller and copy the retrieved data from the database to a lightweight View Model object before executing the View, lightweight View Model objects do not need to retrieve data during View execution.
Use (automatically generated) the client for verification
From ASP. net mvc 2, client verification can be easily added.
(1) Add the data verification logic in the Model layer as described above;
(2) Make sure that the Scripts directory in the project contains the following javascript files: MicrosoftAjax. js and MicrosoftMvcValidation. js;
(3) On the form submission page, add the following code:
<Script src = "<% = Url. Content ("~ /Scripts/MicrosoftAjax. js ") %>" type = "text/javascript"> </script>
<Script src = "<% = Url. Content ("~ /Scripts/MicrosoftMvcValidation. js ") %>" type = "text/javascript"> </script>
(4) Add the following code to the form:
<% Html. EnableClientValidation (); %>
If you edit the form content, the client immediately sends a verification reminder when the input value is invalid.
Insert server-side in the templateNote
Use server comments in the View template and remove them When HTML is rendered.
The following is a server-side comment:
<% -- This is a server side template comment -- %>
Do not use HTML annotations in the View template, because these annotations are displayed in a web browser and can be viewed by users.
Use HTMLHelperExtension Method.
The System. Web. Mvc. Html class contains many useful HTML extension methods.
Form generation (BeginForm)
Input field generation (checkbox, hidden, radio button, textbox)
Link URL generation (ActionLink)
XSS protection (Encode)
Use these HTML extension methods as much as possible. The following is a link created using route table:
<% = Html. ActionLink ("Home page", "Default") %>
For more information, see the following link:
ASP. net mvc best development practices (2)
ASP. net mvc best development practices (3)
Link to the original English text:
Best Practices for ASP. NET MVC
Http://blogs.msdn.com/ B /aspnetue/archive/2010/09/17/second_2d00_post.aspx