asp.net MVC data validation and related content _ practical skills

Source: Internet
Author: User
Tags server memory

First, data validation

Steps for data Validation add validation-related attribute tags to the model class to import validation-related JS files and CSS files on the client using validation-related HTML helper methods on the server side to determine whether common validation tokens are validated through the server side

Required: Non-null authentication stringlength: Verify string length regularexpression: Regular expression Validation compare: Compare two field values for equality range: Scope Validation Remote: Server Authentication ( Need to write a return value of Jsonresult action in controller custom validation token and validation-related JS files

The ASP.net MVC provides 2 sets of validation frameworks, namely, the Microsoft Validation Framework and the jquery validation framework. The jquery validation framework is enabled by default.

Note: The order of these JS files cannot be reversed; the style used for data validation is defined in the Site.css file.

                      

Validating the associated HTML helper method

Note: 1. Html.validationmessage () and html.validationmessagefor () must be used to display the prompt for validation failure;

2. A validated control, such as a text box drop-down list box, must be generated using HTML helper methods to be valid.

                      

On the server side to determine if the model passed validation (server-side validation)

If the MVC validation feature is used in the page, then the backend action must be modelstate.isvalid to determine if the server-side validation is passed. Other business logic code can be executed only through server-side validation

                      

Key points to use:

The validated tag cannot be pure HTML and must use the appropriate HTML helper method

For example: Html.textboxfor (Model=>model. UserName), the validation is valid;

<input type= "text" id= "UserName" name= "UserName"/>, the validation is invalid;

You must use the appropriate Html helper method to display the validation message (Html.validationmessage) The validated control must be placed inside a Html.BeginForm helper method (cannot be a pure <form> tag). Client-side validation is unsafe, Easy to disable or cheat, so be sure to determine whether Modelstate.isvalid is true on the server side.

Action vs. View data transfer

In some cases, the view needs to display more than one piece of data (such as the modified employee information \ Job List \ department list), but when the action returns a view, the view () method can only pass 1 object types of data, so how can other data be passed?

asp.net mvc provides us with 3 options: Viewdata\tempdata\viewbag.

Important: These three properties are available in both controller and view, and you can extract the data in the corresponding properties of the view after the data is stored in the corresponding properties of controller.

ViewData

ViewData is a dictionary type. When you add data to it, you add it as a key value pair.

First add to the ViewData in the action, then you can access the ViewData in the view to extract the data.

                    

ViewBag

ViewBag is a dynamic type of property. The ViewBag attribute was added to ASP.net MVC 3.0.

Dynamic type: Dynamically, which means that you can not define a property for it beforehand, and you can add new properties to it at any time by assigning a value directly to the property.

The following code shows the CLS and Stu two objects in the ViewBag, which are placed in the property ClassInfo and Studentinfo, respectively.

                    

TempData

The use of TempData is very similar to ViewData, which is a dictionary type. What's the difference between them?

The data stored in the ViewData is valid only for the current action of this access. And the data stored in the TempData, in addition to the current action for this visit, It also works for other action on this visit, such as storing data into tempdata in Action1, and can still extract data from Action2 in TempData, even after jumping from Action1 to Action2. and ViewData and ViewBag can't do that. Therefore, the life cycle of the data in TempData is more than that of viewdata| The life cycle in the viewbag is long.

Implementation class of ActionResult

In the ASP.net MVC model, the action responds to various requests from the user, such as returning HTML documents, HTML fragments, JSON data, plain text, files, and so on to the client. In asp.net mvc, the results of responding to the client are implemented by returning objects of the ActionResult type in the action (Action or action) method.

The ActionResult class is an abstract class (an abstract class cannot be instantiated directly).

ActionResult has many implementation classes, and different implementation classes are used to respond to different client results. And there are a number of helper methods available in the Controller class that can quickly create a variety of actionresult.

In actual development, we are more using the helper methods in the Controller class than by manually creating the ActionResult implementation classes.

Viewresult class

The role of the Viewresult class is to respond to a view file in the view directory to the client.

The view () method is provided in the Controller class to quickly return a Viewresult class object.

Contentresult class

This class is used to return a piece of text content to the client (plain text \html ...).

The helper method in the Controller class is: Controller.content (string Content);
                    

Redirecttorouteresult class

The function of this class is to jump from the current action to another action.

The helper methods in the Controller class are: Redirecttoaction ("ActionName", "Controllername")

Redirectresult class

Jumps from the current action to the other URL address on the server side.

The secondary method in the Controller class is: Controller.redirect (string URL)

                    

Jsonresult class

This class is used to return a JSON-formatted string to the client.

The auxiliary method in the Controller class is: Controller.json (object data);

Note: By default, MVC refuses to respond to Ajax requests that are sent in Get mode, and requires the use of jsonrequestbehavior.allowget.

                    

Partialviewresult class

The function of this class is to respond to a partial view file of the views directory to the client. A partial view is a view file that contains only HTML fragments.

The auxiliary method in the Controller class is: Controller.partialview ();

                    

The following illustration shows how to create a partial view file when you create a view file (tick the Create as partial view checkbox):

                    

Filepathresult class

This class is used to implement file downloads.

The secondary method in the Controller class is: Controller.file (string FilePath, String ContentType, string fileName);

                    

Filecontentresult class

Output a byte array in memory directly to the client as a file data. Suitable for dynamically generating files in memory or loading small files into byte arrays for output.

Filestreamresult class

This method first reads the file into the server memory, buffers it, and then sends it to the client. Doing so consumes server memory very much, so avoid sending large files using this method.

Emptyresult class

This class is used to respond to a null result to the client.

Httpstatuscoderesult class

This class is used to specify the status code for the client.

The Httpnotfoundresult class is a subclass of Httpstatuscoderesult that represents the 404 status code.

The following are some common HTTP status codes:

404: The resource was not found (indicates that the client requested the server's resource address does not exist)

500: Server Internal error (the beginning of the 5XX indicates server-side errors that occur during processing)

200: Successful (indicates that the request sent by the client was successfully processed and responded by the server)

Other

How do I import namespaces in an ASPX page?

Mode one: Add <%@ Import namespace= "Namespaces" to the specified page%>

                   

Mode two: Add the pages---Namespaces in the project's Web.config configuration file----add

                   

Note: The namespaces added by way two can be used in all ASPX pages, and the namespaces added by the method can only be used in the current page.

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.