Backcolor = "# ccccff" bordercolor = "black" showfooter = "false"
Cellpadding = "3" cellspacing = "0" font-name = "verdana" font-size = "8pt"
Headerstyle-backcolor = "# aaaadd" enableViewState = "false" />
form>
body>
html>
Most of the code is the same as the code of the previous solution. The main difference is the first line:
<% @ Page language = "c #" codebehind = "solution.aspx.cs" autoeventwireup = "false" inherits = "solution"%> This line tells the ASP.NET execution environment, this page's specific implementation mechanism is in a separate class in. Because this page is independent, this page does not need to do any changes if the code of data accesses changes. Similarly, some designers can also change this page of the page without causing an error in any data access. Model and controller part: The second part of this solution is hidden background code:
Using system;
Using system.data;
Using system.data.sqlclient;
Public Class Solution: System.Web.ui.page
{
Protected system.Web.ui.WebControls.button submit;
Protected system.Web.ui.WebControls.DataGrid mydatagrid;
Protected system.Web.ui.webcontrols.dropdownlist recordingselect;
Private Void Page_Load (Object Sender, System.EventArgs E)
{
IF (! ispostback)
{
String selectcmd = "select * from recording";
SqlConnection MyConnection = New SqlConnection ("Server = (local); Database = Recordings; Trusted_Connection = YES");
Sqldataadapter mycommand = new sqldataadapter (selectcmd, myconnection);
DataSet DS = New Dataset ();
MyCommand.Fill (DS, "Recording");
Recordingselect.datasource = ds;
Recordingselect.DataTextField = "Title";
Recordingselect.datavaluefield = "id";
Recordingselect.database ();
}
}
Void Submitbtn_Click (Object Sender, Eventargs E)
{
String selectcmd = string.format ("Select * from track where recordingid = {0} Order By ID", (String) RecordingSelect.SelectedItem.Value);
SqlConnection MyConnection = New SqlConnection ("Server = (local); Database = Recordings; Trusted_Connection = YES");
Sqldataadapter mycommand = new sqldataadapter (selectcmd, myconnection);
DataSet DS = New Dataset ();
MyCommand.fill (DS, "Track");
MyDataGrid.dataSource = DS; mydatagrid.databind ();
}
#Region Web Form Designer Generated Code
Override protected void oninit (Eventargs E)
{
//
// Codegen: This Call is Required by The ASP.NET Web Form Designer.
//
InitializationComponent ();
Base.onit (E);
}
///
/// Required Method for Designer Support - Do Not Modify
/// The contents of this method with the code editor.
/// summary>
Private vidinitiRizeComponent ()
{
This.Submit.Click = new system.eventhandler (this.submitbtn_click);
This.Load = New System.EventHandler (this.page_load);
}
#ndregion
}
Here will move the code from the previous implementation method to a file in its own file. The views and model controllers are connected to a whole through some mechanisms. If the member variables in this class are the same name as the control used in the Solution.aspx file. Another must be displayed that how the controller connects the behavior to the events thereafter. In this example, the InitializationComponent function is connected to two events. The first one connects the LOAD event with the Page_Load function, the second is the Click event, call the submitbtn_click function when the Submit button is clicked.
The code separation is an excellent mechanism that separates the view part and the model and controller part. But when you want to remove the code from the isolated background to other pages, it may be insufficient. Technically, the code reuse behind the page is feasible, but as you need to share the increase in the page, it is difficult to connect the page with the background code. Model - View - Controller Separation In order to solve the problem left by the above, you must separate the model to the controller role. The implementation code of the view is the same as the front portion. The code example below makes the model role only depends on the database without including any code-dependent code.
using System; using System.Collections; using System.Data; using System.Data.SqlClient; public class DatabaseGateway {public static DataSet GetRecordings () {String selectCmd = "select * from Recording"; SqlConnection myConnection = new SqlConnection ( "server = (local); database = recordings; Trusted_Connection = yes "); SqlDataAdapter myCommand = new SqlDataAdapter (selectCmd, myConnection); DataSet ds = new DataSet (); myCommand.Fill (ds," Recording "); return ds;} public static DataSet getTracks (string recordingId) {String selectCmd = String.Format ( "select * from Track where recordingId = {0} order by id", recordingId); SqlConnection myConnection = new SqlConnection ( "server = (local); database = recordings; Trusted_connection = yes "); sqldataadapter mycommand = new sqldataadapter (selectcmd, myconnection); DataSet DS = new dataset (); mycommand.fill (DS," track "); return ds;} The current code only depends only on the database, this class It is a channel of an excellent database that holds the SQL statement used to access the table or view, and the other code calls some methods to complete The interaction of the database. Controller This reconstruction manner utilizes the code hidden mechanism, and the controller is responsible for the control of the event and method in the case where the model portion responsible for data access is relatively independent. The task of the model is clear, it only returns a DataSet object. This implementation is like view code, and does not rely on how the data is returned from the database.
Using system;
Using system.data;
Using system.collections;
Using system.Web.ui.webcontrols;
Public Class Solution: System.Web.ui.page
{
Protected system.Web.ui.WebControls.button submit;
Protected system.Web.ui.WebControls.DataGrid mydatagrid;
Protected system.Web.ui.webcontrols.dropdownlist recordingselect;
Private Void Page_Load (Object Sender, System.EventArgs E)
{
IF (! ispostback)
{
DataSet DS = DatabaseGateway.getRecordings ();
Recordingselect.datasource = DS; RecordingSelect.DataTfield = "Title";
Recordingselect.datavaluefield = "id";
Recordingselect.database ();
}
}
Void Submitbtn_Click (Object Sender, Eventargs E)
{
DataSet DS = DatabaseGateway.gettracks (String) RecordingSelect.SelectedItem.Value;
MyDataGrid.dataSource = DS;
MyDataGrid.databind ();
} #Region Web Form Designer Generated Code
Override protected void oninit (Eventargs E)
{
//
// Codegen: This Call is Required by The ASP.NET Web Form Designer.
//
InitializationComponent ();
Base.onit (E);
}
///
/// Required Method for Designer Support - Do Not Modify
/// The contents of this method with the code editor.
/// summary>
Private vidinitiRizeComponent ()
{
This.Submit.Click = new system.eventhandler (this.submitbtn_click);
This.Load = New System.EventHandler (this.page_load);
}
#ndregion
}
test
Separating the model portion from the ASP.NET environment enables the model portion to be tested more easily. In the ASP.NET environment, you must test a lot at the same time, such as whether the HTML code is correct, and reading the HTML code is very bored. Separate the model part so you can make a separate unit test on the model portion. The following is an example of unit testing of the model section below NUnit (http://nunit.org).
using System; using NUnit.Framework; using System.Collections; using System.Data; using System.Data.SqlClient; [TestFixture] public class GatewayFixture {[Test] public void Tracks1234Query () {DataSet ds = DatabaseGateway.GetTracks ( "1234 "); Assertion.assertequals (10, ds.tables [" track "]. Rount);} [test] public void tracks2345Query () {DataSet DS = DatabaseGateway.gettracks (" 2345 "); assertion.assertequals (3 , ds.tables ["track"]. rount);} [test] public void recordings () {dataset ds = DatabaseGateway.getRecordings (); assertion.assertequals (4, ds.tables ["replaording"]. Rows .Count); dataable recording = ds.tables ["replaording"]; assertion.assertequals (4, replaording.rows.count); DATAROW FIRSTROW = Recording.Rows [0]; string title = (string) FIRSTROW ["Title" ]; Assertion.assertequals ("up", title.trim ());}} Conclusion: The MVC mode is implemented in ASP.NET has the following advantages and disadvantages: advantage: can reduce dependence. The programmer can implement all the code in an ASP.NET page. Single page implementation, for some small and long-lived programs are applicable. However, if you want to share the code between the increasing pages, it is very effective. Ability to reduce the copy of the code. The GetRecordings and GetTracks methods in the Databasegateway class can be used directly by other pages, reducing the case where the code must be copied to different pages. Ability to separate the responsibility of different people. Modifying the appearance of the page and the technique used by the code to modify the data accessed is different, and the model is separated from the view to the work of experts responsible for different work.
Make performance optimization may be possible to divide different classes into different classes to make performance optimization. In the previous example, data is read from the database since each request page is requested. Therefore, the data can be cached in some case, thereby increasing the performance of the entire program. If you don't separate the code, you cannot do this. Easy testivity The model is separated from the view into unit testing in an ASP.NET environment. Disadvantages: Increase the number and complexity of the code. This example adds new files and code based on the implementation of the earlier single page, and the maintenance overhead is added in invisible. Once the system is modified, the code for all three roles will be modified. In some cases, modifications in a file are more convenient than modifying in some files. So when considering whether you use the MVC mode. This additional overhead must be calculated, for some small programs, this overhead is not worth it.