Professional ASP. NET WEBFORMS/MVC Control library based on JQuery!

Source: Internet
Author: User
Tags button type naming convention actionlink

Directory

First ASP. NET MVC QuickStart Database Operations (MVC5+EF6)

"Second" ASP-Quick Start Data annotations (MVC5+EF6)

"Third" security policy for the Quick start of ASP. NET MVC (MVC5+EF6)

"Fourth" complete example of the ASP. NET MVC QuickStart (MVC5+EF6)

The Free jquery Control Library (MVC5+EF6), "Foreign article", the Quick start of ASP.

Please pay attention to the three stone blog: Http://cnblogs.com/sanshi

New Project

Open the VS2015, locate the menu item [file-New project], Open the wizard dialog box:

Note Our selection:

    1. Running platform:. NET FrameWork 4.5
    2. Project template: ASP. NET WEB Application
    3. Project name: Aspnetmvc.quickstart, if you are following this tutorial, suggest the same project name, which is handy for copying the code directly into your project.

Click the [OK] button and the wizard will take us to another selection dialog box:

Since this tutorial is quick to get started, let's start with the simplest, just tick the required options:

    1. No authentication is performed. ASP. NET MVC provides a comprehensive authentication scheme, and we will have a separate article to explain.
    2. Only the MVC reference is checked.

Click [OK],vs2015 will create a project that can run directly, press the shortcut key [Ctrl+f5], do not debug directly run:

The default directory structure is as follows:

If you have previously developed under WebForms, you should be familiar with some of these folders and files:

    1. Web. config: The project configuration file, which holds the project configuration parameters and the database connection string.
    2. Packages.config:Nuget configuration file
    3. Global.asax: A global code file that provides application-level and session-level event handlers that can register global variables in Application_Start.
    4. Favicon.ico: The browser address bar icon, referenced in the HTML head tag.
    5. App_Data: Place local database files, such as LocalDB generated database files.

The following folders, used to place static files, can be easily guessed by name:

    1. Scripts: Place static script files, such as jquery.
    2. Fonts: Place icon font files, such as popular fontawesome fonts.
    3. Content: Place static files, such as XML files, bootstrap CSS libraries.

The following files are newly introduced by asp:

    1. App_start: Used to place the application initialization class, this is a naming convention introduced by MVC4, in fact, this is an ordinary folder, no special meaning.
    2. Controllers: Controller class.
    3. Models: Model classes, such as the model definition for EF codefirst.
    4. Views: View files, the original view engine is WebForms view engines, using the same syntax as the ASPX file, and now the Razor view engine is MVC3 introduced with cshtml as the suffix.

Page Flow

First look at the [about] page:

This page was presented to us and experienced three main processes:

    1. The MVC routing engine finds the appropriate controller (HomeController.cs) based on the URL.
    2. The operation method of the controller is about preparing the data and then passing in the view home/about.cshtml.
    3. The view prepares the HTML fragment, puts it in the layout page and returns to the browser.

Controller, routing Engine

Everything has to be said from the Global.asax. In the application Enablement event, we need to register the routing processor:

protected void Application_Start () {       arearegistration.registerallareas ();       Filterconfig.registerglobalfilters (globalfilters.filters);       routeconfig.registerroutes (routetable.routes);       Bundleconfig.registerbundles (bundletable.bundles);}

RouteConfig.cs class is located in the App_start folder, let's look at the content:

public class routeconfig{public       static void RegisterRoutes (RouteCollection routes)       {              routes. Ignoreroute ("{resource}.axd/{*pathinfo}");               Routes. MapRoute (                     name: "Default",                     "{controller}/{action}/{id}",                     defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}              );}       }

Here, a routing rule named default is registered, and the corresponding URL is {controller}/{action}/{id}, where three placeholders are represented:

    1. {Controller}: Director, default is home, the corresponding controller class is HomeController.cs.
    2. {Action}: The method inside the controller, which is index by default. So if the user accesses the system directly through http://localhost/, the default call to the index method in the home controller is processed.
    3. {ID}: Parameter id, optional, this parameter corresponds to the ID parameter in the action method.

View, Controller method

Through the above introduction, we know the Http://localhost:55654/Home/About URL corresponds to the Home controller's about method.

We found the appropriate method in the Controllers/homecontroller.cs:

Public ActionResult About () {       viewbag.message = "Your Application description page.";        return View ();}

ViewBag is a dynamic object that can be used to store arbitrary parameters that are used to pass data from the controller to the view.

There are two general ways to pass data from a controller to a view:

    1. Passing in the model, and then accessing it through a model object in the view, is a strongly typed approach and is recommended. The limitation is that only one model can be passed in, and if you need to pass in multiple model objects, you need to customize the class to contain multiple models, and the other is viewbag.
    2. ViewBag, it is convenient to pass data to a view package, but you may need to force type conversions in the view. In the common introduction of a master model and multiple sub-models, multiple models can be put into viewbag to avoid the hassle of custom classes.

As a naming convention, this action method automatically invokes the corresponding name of the view file about.cshtml.

View-Browser

Here's a look at the about.cshtml view file:

@{    viewbag.title = "About";} 

With the start of the @ to output the results of the C # code, MVC automatically determines where to end the C # code and into the HTML code.

Note that the @{} on the first line of the page is used to execute a section of C # code, does not output content, defines a viewbag.title variable, and uses @viewbag.title output to the page in the following code.

Many beginners may be wondering why viewbag.message is defined in the controller, and Viewbag.title is defined in the view, what is the difference between the two?

In general there is no functional difference, just a semantic difference. The variables defined in the view are used only in the view, such as the viewbag.title defined here is not only used in about.cshtml, but also in the layout view shared/-_layout.cshtml.

Layout view

The layout view is similar to the master page in WebForms, and the specific view page is embedded as part of the layout view and then returned to the browser to form a complete page.

Each view page uses the content defined in views/_viewstart.cshtml by default:

@{    Layout = "~/views/shared/_layout.cshtml";}

This specifies the location of the layout view, so let's simply look at the contents of the Layout view:

<! DOCTYPE html>@ViewBag. Title -My ASP. Application</title> @Styles. Render ("~/content/css") @Scripts. Render ("~/bundles/modernizr") 

@RenderBody ()

The Viewbag.title attribute defined in the about view is used in the title below the head tag.

This layout view is done using the CSS style defined by the bootstrap library, including the title bar, navigation menu, and footer definition, where the specific content will be embedded in the @renderbody () and eventually form a full HTML page back.

Database operations

The data passed into the view from the controller above is a hard-coded string, the actual project often needs to read from the database, we use the Microsoft recommended entity Framework Codefirst Development mode to create and use the database.

Installing the Entity Framework

First you need to install EF, find the [Tools] menu in VS2015, and find the NuGet Package Manager:

Go to the Browse tab and you can search the entity Framework to install its latest stable version into your project:

After installation, the Web. config is automatically changed to add the appropriate configuration information.

Create a model

We plan to complete a simple student management system that includes basic additions and deletions (CRUD).

First in the models file, create the student (Student) model class:

public class student{Public       int ID {get; set;}       public string Name {get; set;}       public int Gender {get; set;}       public string Major {get; set;}       Public DateTime entrancedate {get; set;}}

Then create the database operation context, which EF needs to create and access the database:

public class studentdbcontext:dbcontext{Public       dbset<student> Students {get; set;}}

Since this class inherits from the DbContext base class of EF, it is necessary to add the following reference to the file header:

Using System.Data.Entity;

After you create these two files, you need to recompile the project (shortcut key ctrl+shift+b), or you will get an error adding the controller below.

Add Controller

Right-click on the Controllers directory, add controller, and Pop Up the wizard dialog box:

Here you choose MVC 5 Controller with views, using the Entity Framework, and then go to the Settings dialog box:

In this dialog, we need to specify the model class (Student) and the data Access Context class (Studentdbcontext) that we just created, and then vs can not only create the view automatically, but also use EF to automatically create all the crud's code, isn't it cool!

All features are complete!

Isn't it amazing that we didn't even have time to write the view code, no configuration database, no logic code to write crud, vs template to help us build everything, run it Now (CTRL+F5), and enter/students in the browser:

Table page

The table page corresponds to the index action method under the students controller:

public class studentscontroller:controller{       private Studentdbcontext db = new Studentdbcontext ();        Get:students public       ActionResult Index ()       {              return View (db. Students.tolist ());       }      }

First, we see that the controller internally defines a private variable, db, and initializes it. This is a database operation context instance, and all crud operations are dependent on this instance.

In the Index method, the model data is passed to the view by passing a student list to the view method, and in the views/students/index.cshtml view file, we declare the type of the incoming model:

@model ienumerable<aspnetmvc.quickstart.models.student>

In the view, the type of the model property is determined to be strongly typed Ienumrable<student>, and with the IntelliSense provided by VS, not only can you quickly write code, but also check the validity of the code at compile time.

The Complete index.cshtml code:

@model ienumerable<aspnetmvc.quickstart.models.student> @{viewbag.title = "Index";} 

Look at the feeling of an old ASP, but the model property here is strongly typed, so in the Foreach loop, vs is explicitly aware that the item type is student, which facilitates code writing:

@Html are all the auxiliary methods provided by MVC to assist in generating HTML code:

    1. ActionLink: Used to generate hyperlinks, link to an action method within the controller (also can be a method of another controller, have overloaded functions), you can specify the route parameters, through the object initialization syntax to create, such as new {id=item.id}.
    2. Displaynamefor: Displays the name of the model property. Strongly-typed helper methods allow us to use a lambda expression to specify a model property without writing a string. The benefits are not only IntelliSense, compile-time checking, but also code refactoring, such as when we change the property name of the model, the corresponding code in the view changes.
    3. Displayfor: Displays the value of the Model property.
New Page

The new page corresponds to the Create operation method under the students controller:

Get:students/createpublic ActionResult Create () {       return View ();}

The corresponding view file:

@model AspNetMvc.QuickStart.Models.Student @{viewbag.title = "Create";} 

First, the model type used in the view is defined as student, so that the Labelfor strongly typed helper method can get the text that needs to be displayed from the model metadata.

When the page is open, the model is an empty object because it has not been passed in, as follows:

So the default input box on the page is empty, which is the effect of the author's input value.

Html.BeginForm () generates a form label on the page, the default submission address or the current page (action=/students/create), and the default request method is post, as follows:

Therefore, when the [Create] button is clicked, a POST request is issued to the background, corresponding to the Create method of the students controller.

Save data and model bindings

Let's look at the Create method with [HttpPost] metadata:

[HttpPost] [Validateantiforgerytoken]public actionresult Create ([Bind (Include = "id,name,gender,major,entrancedate")] Student Student) {       if (modelstate.isvalid)       {              db. Students.add (student);              Db. SaveChanges ();              Return redirecttoaction ("Index");       }        Return View (student);}

There are two safety measures in this:

    1. Validateantiforgerytoken: Used to block CSRF (cross-site request forgery).
    2. Bind: Used to block over-posting (excessive commit attacks).

These two safety measures will be introduced in detail in a later article, this is the first to skip.

Let's look at the post parameters for this request first:

But it is not surprising that there is only one student object parameter in the Create method, which is actually an important conceptual model binding .

If we were in WebForms, we could write a bunch of code to get the parameters from the Request.Form and reconstruct the student object, similar to the following code:

Student Student = new Student (); Student. Name = request.form["Name"];student. Gender = Convert.ToInt32 (request.form["Gender"]);

In MVC, this process is done automatically, which is simply a model binding.

However, the actual model binding process is not only looked up in the requested form data, but also in the routing parameters, URL query strings, and cookies.

If the model binding fails (for example, the model parameter does not conform to the validation rule), Then Modelstate.isvalid is false, this will directly return to the page content, when the model object student is saved in the user input values, the front end will also have errors, this process we will explain in the next article.

If the model binding succeeds, the new data is saved and then redirected to the table page via redirecttoaction:

Summary

This article first introduces the process of creating an MVC project under VS2015, and then briefly outlines the process of page execution, from the routing engine to the controller, from the controller to the view, and finally from the view to the browser, and the model is a parameter that is passed into the view as a controller, which is clear, and finally using the VS template A data access instance with a CRUD operation was created.

EF Codefirst has shifted our focus from the database to the model, and the model is the core of MVC, the appropriate data annotations to the model, not only affect the database table structure, but also affect the browser side of the data validation and server-side data validation, So in the next article we'll look at the data annotations in detail.

Download Sample source code

Professional ASP. NET WEBFORMS/MVC Control library based on JQuery!

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.