ASP. net mvc 1.0 learning notes

Source: Internet
Author: User

ASP. net MVC 1.0 is newly released, and the header allows me to use it for projects. to be honest, I had no idea at first. although ASP. net web form is not very familiar with, but I have done it for a while, and I still have a thorough understanding. in addition to a basic concept, MVC has no specific implementation knowledge. but I thought it was always good to learn something new, and I was probably able to handle it, so I tried to use it.
The first thing is ASP. net MVC official homepage download library, installation is OK. then, find references. because it is too new and has very few e-books, it is hard to find only one ASP. net MVC in action preview, an ASP. net MVC 1.0 quickly, professional Asp.net MVC Framework Chapter 1. first look at ASP. net MVC in action, I think it is hard to understand, but also look at ASP. net MVC 1.0 quickly, started to feel very good, the context is clear, the content is practical, but after a few days, I felt that the content is not rich enough, and finally it was an instance, it is not practical. in this way, many things can only be answered by Google.
After fighting with this ghost thing for a few days, I finally got a little bit enlightened and wrote something:
1. Basic concepts of MVC:
The main purpose is to achieve separation of data and data performance, reduce coupling, and make the program more flexible. when a view needs data, it sends a request to the controller. The controller obtains data through the model and then sets the view presentation form.
2. Main differences between ASP. net mvc and the original ASP. NET web form:
The original ASP. net web form, basically all events occur on the server. The client calls the server through PostBack, and the server sends the results to the client after processing. there are many server-side controls, and there are many similarities between the programming mode and win form, such as event-driven and rich controls.
ASP. net MVC requires the user to handle the PostBack, or control the PostBack by programming the controller. Naturally, this increases flexibility and gives the client more room to play. however, since the server control is canceled, programming is not as convenient as web form. For example, without the calendar control, you can only use JavaScript as one; the view generated by the controller can be seen at runtime (rather than during design), and the WYSIWYG interface design is gone.
There is also a big difference: Asp. net MVC introduces the concept of routing. previously, in web form, a URL corresponds to a physical file on the disk. In MVC, a URL corresponds to the name of an Action Method in controller.

3. Basic Structure of ASP. net mvc:
1) client:
It is mainly an HTML page. Although it also uses the aspx suffix, it does not have codebehind in the web form. The page starts with a sentence:
<% @ Page Language = "C #" inherits = "system. Web. MVC. viewpage" %>
In addition to standard HTML elements and JavaScript, you can also use the htmlhelper class to generate controls, such:
<Table>
<Tr>
<TD>
<% = Html. Textbox ("txtcode", String. Empty, new {@ ID = "txtcode", style = "width: 100px"}) %>
The HTML attribute of textbox is enclosed in brackets after new.
Actually it is equal:
<Input type = "text" name = "txtcode" id = "txtcode" value = ''/>
Another unique element is actionlink, which is similar to hyperlink, except that ASP. net MVC uses the concept of routing, so the connection points to not a specific physical file, but a method of the controller class.
2) server:
One is model, which is responsible for accessing the database and providing data, which is not very different from common classes. one is the controller, which is responsible for interacting with the client, presenting data to the client, or adjusting the background data when the client's display changes.
4. Interaction between the client and the server:
1) initial:
Generally, it is the initial MVC in default. aspx. cs. If it is generated using a wizard, default. aspx. CS is the only file with codebehind and page_load events:
String originalpath = request. path;
Httpcontext. Current. rewritepath (request. applicationpath, false );
Ihttphandler httphandler = new mvchttphandler ();
Httphandler. processrequest (httpcontext. Current );
Httpcontext. Current. rewritepath (originalpath, false );
Other pages can be accessed only after the default. aspx is accessed. Otherwise, an error is returned if MVC is not started.
2) routing:
The Controller responsible for processing the default. aspx page is placed in homecontroller. CS under the controllers directory. The content is very simple:
[Handleerror]
Public class homecontroller: Controller
{
Public actionresult index ()
{
// Viewdata ["message"] = "Welcome to ASP. net mvc! ";

Return view ();
}

Public actionresult about ()
{
Return view ();
}
So how does MVC find this?
First, there is a setting in Web. config:
<Add name = "urlroutingmodule" type = "system. Web. Routing. urlroutingmodule, system. Web. Routing, version = 3.5.0.0, culture = neutral, publickeytoken = 31bf3856ad364e35"/>
This default assembly is responsible for routing.
The specific routing settings are generally stored in the global. asax. CS file:
Public static void registerroutes (routecollection routes)
{
Routes. ignoreroute ("{resource}. axd/{* pathinfo }");

Routes. maproute (
"Default", // path name
"{Controller}/{action}/{ID}", // path style with Parameters
New {controller = "home", Action = "Index", id = ""} // default controller and action corresponding to this path and default parameters
);
}

Protected void application_start ()
{
Registerroutes (routetable. routes );
}

For example, http: // localhost: 2040/CAR/check, MVC will find carcontroller under the Controller directory. if the check method in the CS file cannot be found, it will be transferred to homecontroller. the index method in CS.
Note the following:
A. IIS 5.0 (such as installed in 2000 and XP) does not support the so-called wildcard mapping, that is, it does not support no suffix (such. aspx ,. CS), so no matter how set, you can only go to the default homecontroller. to solve this problem, define a suffix, such. MVC, and then in IIS. MVC is associated with aspnet_isapi.dll, and then. asax. add a path ing to CS:
Routes. maproute (
"Myroute ",
"{Controller}. MVC/{action }",
New {controller = "mycontroller", Action = "myaction "}
);
B. the self-added path must be placed before the default path. the reason is that MVC looks for paths in the order of code. If we put the default one before it, it will directly match and the path defined by ourselves will not match.
3) client-server interaction process:
After a URL request is sent, MVC finds the method to process the route according to the set route, that is, action. After setting the interface and data to be displayed, return a view, that is, the page:
Public actionresult index ()
{
// Viewdata ["message"] = "Welcome to ASP. net mvc! ";

Return view ();
}
The view () Here is an HTML page. if there is no parameter, MVC will go to the page with the same name as the method. In this example, go to the views/home directory to find the index. aspx file. if a parameter is specified, for example, return view ("mypage"), find mypage under the views/mypage directory (if this directory exists. aspx. If not, go to the home directory and find mypage. aspx. this is a form.

In another form, if you want to set the values of some elements on the page, such as setting the value of a Textbox, there are two main methods:
One is to pass the value through viewdatadictionary:
Public actionresult index ()
{
// Viewdata ["message"] = "Welcome to ASP. net mvc! ";
Viewdata ["txtcode"] = "test ";
Return view ();
}

Viewdatadictionary is a container that can store everything in the past. It is very easy to retrieve the value from the client, as shown in the textbox defined above:
<% = Html. textbox ("txtcode", String. empty, new {@ ID = "txtcode", style = "width: 100px"}) %>, if the initial value is string. change empty to viewdata ["txtcode"], and the client displays "test ".
Note that viewdata is transmitted in one way, that is, it can only be transmitted from the server to the client.

Another method is to use model. model as an invisible data object on the client. As mentioned earlier, the MVC view page starts with one sentence:
<% @ Page Language = "C #" inherits = "system. web. MVC. viewpage "%>, the viewpage does not specify the type of the model object of the corresponding page. For convenience, you can specify the Data Type of the model as follows:
<% @ Page Language = "C #" inherits = "system. Web. MVC. viewpage <myobjecttype>" %>
In the above index method, add:

Public actionresult index ()
{
// Viewdata ["message"] = "Welcome to ASP. net mvc! ";
Myobjecttype mytype = new myobjecttype ();
Mytype. txtcode = "test ";
Viewdata ["txtcode"] = "test ";
Return view ("Index", mytype );
}


Then rewrite the client statement:
<% = Html. Textbox ("txtcode", model. txtcode, new {@ ID = "txtcode", style = "width: 100px"}) %>,
"Test" can also be displayed ".
A better approach is:
<% = Html. Textbox ("mytype. txtcode", model. txtcode, new {@ ID = "txtcode", style = "width: 100px"}) %>.
The server uses viewdata and model to transmit data to the client.

The client sends data to the server through the submit form. In the preceding example, the server uses request ["txtcode"] or request. Form ["txtcode"] to obtain the value.
If you use the last method above, the HTML element on the front end is fully bound to the model, and you can directly retrieve mytype. txtcode.

5. binding between the client and the server
The client is actually an instance of a model object, assigning a value to its attributes, and then sending it to the server. How are various HTML elements bound to the server?
The simplest is textbox. The server defines a property of the string type, and the client is bound in the form of modeltype. Property.
Checkbox is similar. First, define a Boolean attribute on the server:
Public class mymodeltype
{
Public bool ischecked
{
Get; set;
}
}
Client:
<% = Html. checkbox ("mytype. ischecked", model. ischecked) %>
The trouble is radiobutton. The server must define an Enum type, an attribute of this type, and a bool attribute:
Public class mymodeltype
{
Public Enum enumcheck
{
Yes,
No
}
}
Public enumcheck checkindicator
{
Get; set;
}
Public bool isyeschecked
{
Get; set;
}
Client:
<% = Html. radiobutton ("mytype. checkindicator", "yes", model. isyeschecked) %>
<% = Html. radiobutton ("mytype. checkindicator", "no ",! Modle. isyeschecked) %>
An isyeschecked is defined here, mainly for the initial radiobutton state.
After the client submits the form, the server can check which radiobutton is selected as follows:
If (mytype. checkindicator = mymodeltype. enumcheck. Yes)
{// Select Yes
}

The most troublesome thing is dropdownlist. On the server:
Public class mymodeltype
{
Public selectlist mydropdown
{
Get; set;
}
}

Public actionresult index ()
{
Mymodeltype mytype = new mymodeltype ();
List list = new list ();
List. Add (New selectlistitem {text = "test1", value = "value1 "});
List. Add (New selectlistitem {text = "Test2", value = "value2 "});
List. Add (New selectlistitem {text = "test3", value = "value3 "});
Mytype. mydropdown = new selectlist (list, "value", "text", list [0]. Value); // The last parameter specifies the value selected in the dropdownlist.
Return view ("Index", mytype );
}
On the client:
<% = Html. dropdownlist ("DPL", model. mydropdown) %>
<% = Html. dropdownlist ("mytype. mydropdown ", model. mydropdown) %>. Otherwise, a message indicating no parameter constructor error is displayed when the form is submitted.

6. Other experiences:
Currently, grid is not used. It may be difficult to use MVC. It is not the same as that of gridview.
Jquery, LINQ to SQL, and other new things have not been tried yet.
The biggest disadvantage of this is that the client still lacks support for easy-to-use controls. htmlhelper is too simple. For example, there is no calendar control.
Javascript has more room for display. Many simple functions do not need to be PostBack to the server, affecting performance.
MVC requires a deeper understanding of HTML.

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.