There are several series of tutorials on ASP. net mvc on the Internet, so I will not introduce them from the beginning. I recommend several links at the end. If you need them, you can look at them from the beginning.
1. Introduction of ASP. net mvc and differences between ASP. NET WebForm and ASP. NET WebForm
At the beginning, I tried to find out whether ASP. net mvc was worth it. I thought about it for more than a week, read a lot of materials and comments, and finally decided whether it was worth it. MVC is not a simple design model. It is more like an architecture model or an idea. At first, it came to mind the template engine, NVelocity, StringTempleate, and so on, however, it seems that ASP is not necessary to use the template as an independent front-end design method. net mvc. In most cases, the Repeaterk control and custom control can be used, and c # code can be written on the ASPX page, some complex interface presentation logic can also be implemented using common WebForm. In fact, ASP. the VIEW part of net mvc uses the aspx parser by default. The View section of ASP. net mvc allows you to write some large websites with complicated layout, which is more convenient and more direct at the bottom layer. It is very popular with developers who are familiar with css and js.
After you understand the MVC idea, you will find ASP. net mvc has the advantages of Controller and Action. You can write a piece of code to clearly understand what requests are being processed. After all, web programs process http requests one by one, unlike windows desktop programs, event-based drivers are more intuitive. ASP. net mvc Controller allows you to easily write some web APIs or rest-style interfaces (HttpHandler may be used in the past). These controllers are only responsible for providing data (Specific ActionResult classes, such as JsonResult, criptresult) to the user, such as an Ajax call or View layer.
As for the Model layer, most people on the Internet are implemented using linq to SQL. After all, it is very easy TO use, design tables, and use the LINQ designer TO drag vs.net. In addition, it is strongly typed, and some division methods can be added to the automatically generated code to verify the data validity. In addition, it is more convenient to perform data persistence and query on the Model made by LINQ. You can use DbContext as a class to add, delete, modify, and query functions.
ASP. net mvc provides advanced ideas and convenience, but ASP. NET, for example, some server controls that you previously wrote cannot be used, WebPart, skin, and various data binding controls, however, the Master page can be used, and Asp.net Ajax control toolkit (server) cannot be used, but asp.net ajax library (client js library) can still be used, authorization based on pages and directories cannot be used (because there are no pages and only views), but MemberShip and Forms authentication are still supported. The lifecycle of the standard WebForm has changed, and some events are missing. Now you can write some interceptors (Action interceptor, Result interceptor, and Exception interceptor) to affect the request processing process. There are some differences, in short, there are alternative ways to find the lost items.
2. How can I obtain the value of the ID column generated by the insert statement from the linq to SQL statement?
In fact, it is very simple. After the object is inserted into the database, the value can be taken directly. The following BBSPost is an entity class, where PostID is an auto-incrementing column in the database.Copy codeThe Code is as follows: var db = new BBSDbContext (connstr );
BBSPost post = new BBSPost ()
Post. PostUser = User. Identity. Name;
Post. PostTime = DateTime. Now;
Db. BBSPosts. InsertOnSubmit (post );
Db. SubmitChanges ();
Int postid = post. PostID; // The value of the ID column can be obtained here.
3. In ASP. net mvc, how does one maintain the scroll bar position after the request is submitted?
WebForm is no longer simple. You can configure MaintainScrollPositionOnPostBack = true in web. config, but it won't work in MVC. After learning the principle, we can implement it by ourselves. In fact, we capture the position of the current scroll bar in the event of submitting a form or scroll bar, place the value in a hidden field, and submit it to the server, after the server responds, it extracts the position of the scroll bar from the hidden domain and uses js to manipulate the scroll bar to scroll to the last position.
First, write a hidden field in the View, as shown below:
<% = Html. Hidden ("scroll", ViewData ["scrool"]) %>
Then, store the submitted value in ViewData in the action that processes the client request (from FormCollection ).Copy codeThe Code is as follows: public ActionResult reply (BBSPost post, FormCollection coll ){
...
ViewData ["scroll"] = coll ["scroll"];
...
Return View ("show_post", posts );
}
In this way, after the page is submitted, the hidden domain stores the position of the scroll bar before submission, and then we write some logic with JQuery to achieve the final effect.Copy codeThe Code is as follows: <script type = "text/javascript">
$ (Function (){
$ (Document). scroll (function (){
// Update the position value of the scroll bar in the hidden domain when the scroll bar is rolling. IE8 and Khan are not supported in the test.
$ ("# Scroll" 2.16.val(document.doc umentElement. scrollTop );
});
$ ("Form"). submit (function (){
// Update the position value of the scroll bar in the hidden field when the form is submitted.
$ ("# Scroll" 2.16.val(document.doc umentElement. scrollTop );
Return true;
});
// Retrieve the value of the hidden field from the document. load event and set the position of the scroll bar.
Document.doc umentElement. scrollTop = $ ("# scroll"). val ();
});
</Script>
4. Verify user input
Basically, no program can be used to verify data validity. The combination of LINQ and ASP. net mvc makes data verification easy.
The class automatically generated by the linq to SQL designer is a partial class, which is half a class. You can write a step-by-step class and add some extension methods TO the automatically generated class, as follows, we add a GetRuleViolations method and an IsValid attribute to the object class BBSPost. The GetRuleViolations method verifies the validity of the value assigned to the object class and returns an enumerator with the yield keyword, here you can write your own Data Validity verification logic.
The IsValid attribute calls the GetRuleViolations method internally. If the Count of the returned enumerator is not 0, the Data Validity verification fails.
In addition, we added two lines of code TO the OnValidate Distribution Method TO write invalid data TO the database in the way of linq to SQL. An exception is thrown before writing data TO the database if the Data Validity verification fails.Copy codeThe Code is as follows: public partial class BBSPost {
Public bool IsValid {
Get {return (GetRuleViolations (). Count () = 0 );}
}
Public IEnumerable <RuleViolation> GetRuleViolations (){
If (String. IsNullOrEmpty (Title ))
Yield return new RuleViolation ("the Title must be entered", "Title ");
If (String. IsNullOrEmpty (Content ))
Yield return new RuleViolation ("Content must be entered", "Content ");
Yield break;
}
Partial void OnValidate (ChangeAction action ){
If (! IsValid)
Throw new ApplicationException ("Rule violations prevent saving ");
}
}
RuleViolation is a helper class, which is very simple.Copy codeThe Code is as follows: public class RuleViolation {
Public string ErrorMessage {get; private set ;}
Public string PropertyName {get; private set ;}
Public RuleViolation (string errorMessage ){
ErrorMessage = errorMessage;
}
Public RuleViolation (string errorMessage, string propertyName ){
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
}
When writing an action, capture the exception of the SubmitChanges operation, and add the exception of the custom authentication logic to the ModelState. The ModelState will pass the exception added to the View layer, for the View layer.Copy codeThe Code is as follows: try {
Var db = new BBSDbContext (GlobalHelper. Conn );
Post. PostUser = User. Identity. Name;
// Other value assignment operations
Db. BBSPosts. InsertOnSubmit (post );
Db. SubmitChanges ();
ModelState. Clear ();
}
Catch (Exception ex ){
ModelState. AddModelErrors (post. GetRuleViolations ());
ModelState. AddModelError ("exception", ex );
}
The default ModelState does not have the AddModelErrors method, but only the AddModelError method. We then added an extension method to him, as shown below:
Public static class ModelStateHelpers {
Public static void AddModelErrors (this ModelStateDictionary modelState, IEnumerable <RuleViolation> errors ){
Foreach (RuleViolation issue in errors ){
ModelState. AddModelError (issue. PropertyName, issue. ErrorMessage );
}
}
}
The Html. ValidationMessage method is used in the View layer to output the error description at an appropriate position. If an error occurs in ModelState when the View is displayed, the corresponding error description is automatically displayed. The sample code is as follows.Copy codeThe Code is as follows: <p>
<Label for = "Title">
Title: </label>
<% = Html. TextBox ("Title", null, new {style = "width: 700px;"}) %>
<% = Html. ValidationMessage ("Title") %>
</P>
<P>
<Label for = "Content">
Content: </label>
<% = Html. TextArea ("Content", null, new {style = "width: 700px; height: 100px;"}) %>
<% = Html. ValidationMessage ("Content") %>
</P>
5. Paging from LINGQ TO SQL
SQLSERVER 2005 has powerful paging functions, and linq to SQL is well supported. The IQueryable <T> Skip and Take method generate paging SQL, first, write the following help class (from NerdDinner). The attributes of this class are very simple. If you know your name, you will not introduce it.Copy codeThe Code is as follows: public class PaginatedList <T>: List <T> {
Public int PageIndex {get; private set ;}
Public int PageSize {get; private set ;}
Public int TotalCount {get; private set ;}
Public int TotalPages {get; private set ;}
Public PaginatedList (IQueryable <T> source, int pageIndex, int pageSize ){
PageIndex = pageIndex;
PageSize = pageSize;
TotalCount = source. Count ();
TotalPages = (int) Math. Ceiling (TotalCount/(double) PageSize );
This. AddRange (source. Skip (PageIndex * PageSize). Take (PageSize); // this statement stops loading delays and loads data into the memory.
}
Public bool HasPreviousPage {
Get {
Return (PageIndex> 0 );
}
}
Public bool HasNextPage {
Get {
Return (PageIndex + 1 <TotalPages );
}
}
}
It is very easy TO use. After obtaining an IQueryable using linq to SQL, use its New PaginatedList TO represent a paginated dataset.Copy codeThe Code is as follows: var posts = from post in db. BBSPosts
Where post. CategoryID = id & post. ParentID = 0
Orderby post. PostID descending
Select post;
Const int pageSize = 10;
Var pagePosts = new PaginatedList <BBSPost> (posts, page ?? 0, pageSize );
Return View (pagePosts );
Posts is an IQueryable <BBSPost> object generated using linq to SQL. At this time, the SQL statement is not executed and execution is delayed, when a new PaginatedList <BBSPost> is added, the generated SQL statement is modified, and the pagePosts is passed to the view layer for use. The View layer uses a strong View, as follows:
<% @ Page Title = "" Language = "C #" MasterPageFile = "~ /Views/Shared/Site. Master"
Inherits = "System. Web. Mvc. ViewPage <SimpleBBS. Helpers. PaginatedList <SimpleBBS. Models. BBSPost>" %>
The link on the previous page and next page is easy to write.Copy codeThe Code is as follows: <div class = "pagination">
<% If (Model. HasPreviousPage) {%>
<% = Html. RouteLink ("Previous Page ",
"Default ",
New {page = (Model. PageIndex-1)}) %>
<% }%>
<% If (Model. HasNextPage) {%>
<% = Html. RouteLink ("next page ",
"Default ",
New {page = (Model. PageIndex + 1)}) %>
<% }%>
</Div>
6. How can I view the SQL statements generated by linq to SQL?
Some people suspect that the performance of linq to SQL is poor and think that the statements it generates are unreliable. In fact, all statements it generates are parameterized queries, generally, queries based on primary keys or index columns and most update operations should not perform worse performance than handwritten SQL statements. If you are still not at ease, you can print the SQL statements generated by linq to SQL, to avoid performance query statements.
The following codeCopy codeThe Code is as follows: var db = new BBSDbContext (conn );
Var posts = from post in db. BBSPosts
Where post. CategoryID = 1 & post. ParentID = 0
Orderby post. PostID descending
Select new {post. PostID, post. Title, post. Content };
Db. Log = Response. Output; // trace automatically generated SQL statements
Rpt1.DataSource = posts;
Rpt1.DataBind (); // The SQL query is executed only when the data-used statement is actually executed. Before that, the statement is a statement and the execution is delayed automatically.
The page displays the SQL statements generated by linq to SQL.
SELECT [t0]. [PostID], [t0]. [Title], [t0]. [Content] FROM [dbo]. [bbs_Post] AS [t0] WHERE ([t0]. [CategoryID] = @ p0) AND ([t0]. [ParentID] = @ p1) order by [t0]. [PostID] DESC -- @ p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1] -- @ p1: Input Int (Size = 0; prec = 0; Scale = 0) [0] -- Context: SqlProvider (Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1
If it is changed to the following paging method:Copy codeThe Code is as follows: var db = new BBSDbContext (conn );
Var posts = from post in db. BBSPosts
Where post. CategoryID = 1 & post. ParentID = 0
Orderby post. PostID descending
Select post;
Db. Log = Response. Output;
Rpt1.DataSource = posts. Skip (1*5). Take (5 );
Rpt1.DataBind ();
The following SQL statement is output:
SELECT [t1]. [CategoryID], [t1]. [PostID], [t1]. [ParentID], [t1]. [Title], [t1]. [Content], [t1]. [PostUser], [t1]. [PostTime] FROM (SELECT ROW_NUMBER () OVER (order by [t0]. [PostID] DESC) AS [ROW_NUMBER], [t0]. [CategoryID], [t0]. [PostID], [t0]. [ParentID], [t0]. [Title], [t0]. [Content], [t0]. [PostUser], [t0]. [PostTime] FROM [dbo]. [bbs_Post] AS [t0] WHERE ([t0]. [CategoryID] = @ p0) AND ([t0]. [ParentID] = @ p1) AS [t1] WHERE [t1]. [ROW_NUMBER] BETWEEN @ p2 + 1 AND @ p2 + @ p3 order by [t1]. [ROW_NUMBER] -- @ p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1] -- @ p1: Input Int (Size = 0; Prec = 0; scale = 0) [0] -- @ p2: Input Int (Size = 0; Prec = 0; Scale = 0) [5] -- @ p3: Input Int (Size = 0; prec = 0; Scale = 0) [5] -- Context: SqlProvider (Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1
We can see that all these queries use parameterized queries, instead of spelling SQL statements, and also use the ROW_NUMBER function. Therefore, you can better understand SQLSERVER through linq to SQL.
7. Do I need to authenticate an Action?
Because page-based authorization cannot be used, we have to authorize an Action. For example, to reply to a post, we need to log on, in this case, reply the reply action with the attributes that require authentication, as shown below:
[AcceptVerbs (HttpVerbs. Post), Authorize]
? Public ActionResult reply (BBSPost post, FormCollection coll ){
This method is implemented through AOP injection. For more interceptor examples, or you want to write your own interceptor, You can google some information.
8. How to convert the form data submitted by the user to a strong type.
We all know that the data submitted on the Web page includes Form and QueryString. The data retrieved on the server is of the string type. In the asp era, we need to process parameters one by one. net mvc is very convenient. For example, you have a BBSPost class, which has three attributes: Title, Content, and CategoryId. The form has two text boxes: Title and Content, there is a CategoryId in the address bar parameter. You can directly obtain a BBSPost class in the action, and the attributes are filled with you. You do not need to retrieve strings one by one and then create a new BBSPost class, then convert the type assignment and other operations as follows:
Public ActionResult reply (BBSPost post, FormCollection coll ){}
The first parameter is automatically filled with a strong type, and the second parameter can retrieve the data submitted by the original form. If you want to learn more about the binding of form data and strong data, you can check how defamodelmodelbinder works.
9. Add extension methods to HTMLHelper.
ASP. net mvc, a best practice is to add some common extension methods to HTMLHelper for the View layer for ease of use, do not write help classes everywhere, for example, if you want to format the post into HTML when displaying the post, we have written the following extension method:Copy codeThe Code is as follows: public static class HtmlHelperExtension {
Public static string Text2Html (this HtmlHelper helper, string input ){
Input = input. Replace ("","");
Input = input. Replace ("\ r \ n", "<br/> ");
Input = input. Replace ("\ t ","");
Return input;
}
}
REFERENCE The namespace of the Extension Method on The view.
<% @ Import Namespace = "SimpleBBS. Helpers" %>
The extension method can be used as follows:
<% = Html. Text2Html (Html. Encode (item. Content) %>
10. How to locate scripts and CSS
If there are many directories and scripts and style sheets are placed in a fixed directory, access to these resource paths in specific subdirectories may be inconsistent, only the server control can be used in WebForm ~ Syntax, whether deployed in the site root directory or virtual directory ,~ Can represent the root directory of the application. In ASP. net mvc, we can use Url. Content ~, As follows:
<Script src = "<% = Url. Content ("~ /Scripts/jquery-1.3.2.min.js ") %>" type = "text/javascript"> </script>