In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the knowledge of "how to use models in ASP.NET Core MVC". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Model binding
The model binding in ASP.NET Core MVC maps data from HTTP requests to operation method parameters. Parameters can be either a simple type or a complex type. MVC solves this problem through abstract binding.
two。 Use model binding
When MVC receives a HTTP request, it routes it to an action method specified by the controller. It determines which operation to run based on routing data, and then binds the value from the HTTP request to the parameters of the action method, such as
Http://afei.com/movies/edit/2
Movies/edit/2 routes to the Edit method of the Movies controller through the routing template and receives an optional parameter id. Strings in URL are case-insensitive.
MVC will attempt to bind the request data to the operation parameters by name. MVC looks for each parameter value using the parameter name and its publicly settable property name. In the above example, the only operation parameter is named id, where MVC is bound to a value with the same name in the routing value. In addition to the route value, MVC binds the data for each part of the request and does so in the order in which it is set.
The sequential list of model bindings to find the data source:
1. Form values: form data sent through HTTP POST requests (including jQuery POST requests).
2. Route values: the routing dataset provided by routing.
3. Query string: part of the query string for URL.
Form values, routing data, and query strings are all stored as key-value pairs.
Because the model binding is looking for a key named id, but it's not in the form, look in the routing data next. When binding occurs, the value is converted to 2 of the integer type. The same request using Edit (string id) is converted to the string "2".
If the parameter of the Action method is a class, such as a Movies type, although the class contains properties of both simple and complex types, MVC can also be model bound. It uses reflection and recursion to traverse complex types for matching attributes. The model binding looks for the pattern of parameter_name.property_name to bind values to attributes. If no matching value is found in the form, try binding only through property_name. For collection types, the model binding matches parameter_ name [index] or just [index]. Model bindings do the same with dictionary types, as long as Key is a simple type. Key supports matching field names generated by HTML and Tag Helpers for the same model type. When the binding data created or edited fails validation, the return value causes the form field entered by the user to remain, making it convenient for the user to enter.
In order for binding to occur, the class must have a public default constructor, the member to be bound must be a public writable property, and when binding occurs, the class will only use the public default constructor and then set the property.
When a parameter is bound, the model binding stops looking for a value with that name and continues to bind the next parameter. If the binding fails, MVC will not throw an exception, and you can query the model state error through the ModelState.IsValid property.
When performing binding, you need to consider some special data types:
IFormFile, IEnumerable: one or more uploaded files as part of a HTTP request.
CancelationToken: used to cancel activities in a controller.
These types can be bound to action parameters or properties of the class.
Once the model binding is complete, validation is performed. The default model binding is suitable for most development scenarios, and you can also customize the built-in behavior.
3. Customize the model binding behavior through properties
MVC contains properties that can be specified in the set to behave differently from the default binding source. For example, you can specify whether a property needs to be bound or whether it should occur by using the [BindRequired] or [BindNever] attributes. And you can override the default data source and specify the data source of the model binder.
[BindRequired]: if binding does not occur, a model state error will be added.
[BingNever]: tells the model that the binding is never bound to this parameter.
[FromHeader], [FromQuery], [FromRoute], [FromForm]: use these to specify the exact binding source of the application.
[FromServices]: this feature uses dependency injection to bind the parameters of the service.
[FromBody]: use the configured formatter to bind the data in the request body and select the formatter based on the content type of the request.
[ModelBinder]: used to override the default model binder, bind the source and name.
4. Bind formatted data from the request subject
HTTP request data supports a variety of formats, including JSON, XML, and others. When the [FromBody] attribute is used, it indicates that parameters are to be bound from the request body. MVC uses a set of configured formatters to process request data based on its content type. By default, MVC includes a JsonInputFormatter class to handle JSON data, and of course you can add other formatters to handle XML and other custom formats.
Each operation can have at most one [Frombody] decorated parameter. The ASP.NET Core MVC runtime delegates the responsibility of reading the request flow to the formatter. Once the request flow of the parameter is read, it is usually not possible to read the request flow again to bind other [FromBody] parameters.
ASP.NET selects the input formatter based on the type of Content-Type header and parameter. If you want to use XML or some other format, you must configure it in the Startup.cs file, but first use NuGet to get the Microsoft.AspNetCore.Mvc.Formatters.Xml reference. The startup code is as follows:
Public void ConfigureServices (IServiceCollection services) {services.AddMvc () .SetCompatibilityVersion (CompatibilityVersion.Version_2_1) .AddXmlSerializerForbidden ();}
In the example, we add a XML formatter as a service provided by this MVC application. The options parameter passed to the AddMvc method allows you to add and manage filters, formatters, and other system options from the MVC when the application starts, and then apply various features to the controller class or method to achieve the desired results.
5. Model verification
Before the application stores the data in the database, the application must validate the data. The data must be checked for potential security risks, verify that the type and size are correct and comply with the customized rules. Although the implementation of validation can be redundant and tedious, it is necessary. In MVC, validation can occur on both the client and server sides.
.net has abstracted validation as a validation feature. These features contain validation code, thereby reducing the need for coding.
Public class Movies {public int Id {get; set;} [Required] [StringLength (100)] public string Title {get; set;} [Required] [ClassicMovie (1996)] [DataType (DataType.Date)] public DateTime ReleaseDate {get; set;} [Required] [StringLength (100)] public string Description {get; set } [Required] [Range (0999.99)] public decimal Price {get; set;} [Required] public Genre Genre {get; set;} public bool Preorder {get; set;}}
Common built-in validation properties:
[CreditCard]: verify that the attribute is in credit card format
[Compare]: verify that the two attributes in the model match
[EmailAddress]: verify that the property is in email format
[Phone]: verify that the attribute is in phone number format
[Range]: verify that the attribute value is within the given range
[RegularExpression]: verify that the data matches the specified regular expression
[Required]: required attribute
[StringLength]: verify the maximum length of a string attribute
[Url]: verify that the property is in URL format
MVC supports any feature derived from ValidationAttribute or changes to the model to implement IAlidatableObject that is to create a custom validation feature for validation purposes. Many of the built-in validation features can be found in ystem.ComponentModel.DataAnnotations.
Sometimes we need to validate the model manually, and we can call the TryValidateModel method, such as TryValidateModel (movie).
The state of the model represents a series of validation errors for values submitted in the HTML form. MVC continues to validate the field until the maximum number of errors is reached (default of200). You can configure this maximum value in the ConfigureServices method:
Services.AddMvc (options = > options.MaxModelValidationErrors = 500)
Model verification occurs before the operation of each controller is invoked, and it is the responsibility of the operation method to check the ModelState.IsValid and make the appropriate response. In many cases, the appropriate response is to return some kind of error response and, ideally, to detail the reason for the failure of model validation.
6. Custom validation
The way to implement custom validation is simple, just inherit ValidationAttribute and override the IsValid method. The IsValid method takes two parameters, the first is an object object named value, and the second object is a ValidationContext object named validationContext. Value refers to the value of a field validated by a custom validator.
The following customizes the [ClassicMovie] property, which checks whether the ReleaseDate year of the Movies class is greater than 1960:
Public class ClassicMovieAttribute:ValidationAttribute {private int _ year; public ClassicMovieAttribute (int Year) {_ year = Year;} protected override ValidationResult IsValid (object value, ValidationContext validationContext) {Movies movie = (Movies) validationContext.ObjectInstance If (movie.ReleaseDate.Year > _ year) {return new ValidationResult ("release year cannot be greater than" + _ year);} return ValidationResult.Success;}}
This example is valid only for Movies types because the Movies type is hard-coded in the IsValid method. A better option is IValidationObject.
By implementing the Validate method on the IValidatableObject interface, you can put the same code in the model. Although custom validation properties are used to validate individual attributes, implementation IValidationObject can be used to implement class-level validation
Public class Movies: IValidatableObject {private int _ classicYear = 1960; public int Id {get; set;} [Required] [StringLength [100)] public string Title {get; set;} [Required] [DataType (DataType.Date)] public DateTime ReleaseDate {get; set;} [Required] [StringLength (100)] public string Description {get; set } [Required] [Range (0999.99)] public decimal Price {get; set;} public bool Preorder {get; set;} public IEnumerable Validate (ValidationContext validationContext) {if (ReleaseDate.Year > _ classicYear) {yield return new ValidationResult ("release year cannot be greater than" + _ classicYear,new [] {"ReleaseDate"}) } 7. Client authentication
Client-side authentication brings great convenience, it can save time, do not have to spend a round trip waiting for the server verification results.
You must reference the Javascript script for client-side authentication
Jquery-x.x.x.min.js jquery.validate.min.js jquery.validate.unobtrusive.min.js
In addition to the type metadata for model properties, MVC validates the data through Javascript using Attribute and displays all error messages. When MVC is used to render form data that uses Tag Helper or HTML Helpers, it adds HTML 5 data- attributes to the form elements that need to be validated, as shown below, MVC generates the data- feature for built-in validation Attribute and custom validation Attribute. You can display validation errors on the client side through Tag Helper:
The HTML rendered by the above Tag Helper is as follows. Note that in the output HTML, the data- attribute corresponds to the verification Attribute of the Name attribute, and the data-val-required attribute contains an error message. If the ReleaseDate field is left empty, the error message will be displayed with it:
Id ReleaseDate
Client-side validation prevents form submission until it is valid. The submit button executes Javascript code whether the form is submitted or an error message is displayed.
MVC determines the type property value based on the data type of the .NET property. You can use the [DataType] feature to override. The underlying [DataType] feature is not true server-side validation. Browsers choose their own error messages and display them, but Jquery Validation Unobtrusive packages can rewrite messages and make them display in a consistent way.
8. Remote verification
Remote authentication is a good feature when you need to use data on the server for authentication on the client. For example, an application needs to verify that a user name is already in use and needs to query a large amount of data before it can be executed. Downloading a large amount of data verification can take up a lot of resources and may also expose sensitive information. Another way is to use a backhaul request to verify.
Remote validation can be achieved in two steps, and you must first annotate the model properties using the [Remote] feature. The [Remote] feature accepts multiple overloads and can be used to direct the client Javascript to the appropriate code to be invoked. The following code executes the VerfyUser method of the Users controller:
Public class User {[Remote (action: "VerfyUser", controller: "Users")] public string Name {get; set;}}
Then implement the method in the VerfyUser method, which returns a JsonResult:
Public class UsersController: Controller {public IActionResult VerfyUser (string name) {if (! _ usersRepository.VerfyUser (name)) {return Json (data:$ "{name} already exists");} return Json (data:true);}}
Now, when the user enters a name, the JavaScript in the view makes a remote call to validate.
That's all for the content of "how to use models in ASP.NET Core MVC". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.