In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you what are the model binding and verification methods of asp.net core series. I hope you will get something after reading this article. Let's discuss it together.
one。 Model binding
Model binding in ASP.NET Core MVC maps data in HTTP requests to action method parameters. These parameters can be simple types of parameters, such as strings, integers, or floating-point numbers, or complex types. When MVC receives a HTTP request, it routes the request to the controller's specified action method. The default route template is {controller=Home} / {action=Index} / {id?}
/ / for example: request URL http://contoso.com/movies/edit/2 / / map to movies/edit/2public IActionResult Edit (int? Id)
The above Url request corresponds to the Edit method under the movies controller, which accepts an optional parameter named id. MVC binds the id parameter in Edit to a value with the same name in the routing value. Strings in URL routes are case-insensitive.
The parameters bound in the above example are simple types, and if the parameters are a class, such as the Movie type, which contains simple and complex types as properties, MVC's model binding can still handle it well. It uses reflection and recursion to traverse properties of complex types that match (such as Collection, Dictionary).
If the model binding fails, MVC will not raise an error and the parameter value will be null. If the data in the HTTP request is a value entered by the user, you should use the ModelState.IsValid attribute check in the action instead of checking it manually.
Note: to implement model binding, the class must have a public default constructor and public writable properties to bind. When model binding occurs, the property cannot be set until the class is instantiated using the public default constructor.
After the model binding is complete, model validation occurs. For most development scenarios, the default model binding is excellent. It can also be extended to customize built-in behaviors such as model binding features, global custom model binding and validation, formatted data in the body of the binding request (JSON, XML, and many other formats), and custom model binding in advanced articles if you have special needs. There are no instructions here, please check the documentation.
two。 Model verification
The application must validate the data before it can be stored in the database. In MVC, validation occurs on both the client and the server.
2.1 validate attributes
Validation properties are a method of model validation, which is conceptually similar to validation of fields in a database table. Validation attributes are specified at the attribute level. Here is an example:
Public class Movie {public int Id {get; set;} [Required] [StringLength (1960)] public string Title {get; set;} [ClassicMovie (1960)] [DataType (DataType.Date)] public DateTime ReleaseDate {get; set;} [Required] [StringLength (1000)] public string Description {get; set;} [Range (0, 999.99)] public decimal Price {get; set;} [Required] public Genre Genre {get; set;} public bool Preorder {get; set }}
Common built-in validation properties include: [CreditCard] credit card format, [Compare] match two properties, [EmailAddress] mail format, [Phone] phone format, [Range] within a given range, [RegularExpression] regular expression, [Required] must attribute value, [StringLength] maximum length, [Url] URL format, and can also include custom validation properties (such as ClassicMovie). Refer to the official website for all built-in validation attributes
2.2 Custom Verification
The above validation properties apply to most validation requirements. However, some validation rules are specific to your business. It is easy to create custom validation properties in MVC. Simply inherit from ValidationAttribute and override the IsValid method. The IsValid method takes two parameters, the first is an object named value, and the second is a ValidationContext object named validationContext. Value refers to the actual value in the field to be validated by the custom validator.
/ Custom verification / public class ClassicMovieAttribute: ValidationAttribute {private int _ year; / validation rule value / public ClassicMovieAttribute (int year) {_ year = year;} protected override ValidationResult IsValid (object value, ValidationContext validationContext) {Movie movie = (Movie) validationContext.ObjectInstance / / users cannot set the genre of movies released after 1960 to Classic if (movie.Genre = = "Classic" & & movie.ReleaseDate.Year > _ year) {return new ValidationResult (GetErrorMessage ());} return ValidationResult.Success;} private string GetErrorMessage () {return $"Classic movies must have a release year earlier than {_ year}.";}}
To run the program, ReleaseDate is 1989, Genre is Classic, click Save, the verification is carried out on the server side, and an error message is displayed without front-end js verification, as shown below:
2.3 introduction to client-side js authentication
JQuery non-intrusive validation script is a custom Microsoft front-end library built on the popular jQuery Validate plug-in. The principle of client-side validation is that MVC's tag helper and HTML helper can use validation features and type metadata in model properties to render HTML 5 data- attributes in form elements that need to be validated. MVC generates data- attributes for built-in model properties and custom model properties. Then, jQuery non-intrusive authentication analyzes the data- attribute and passes the logic to jQuery Validate, effectively "copying" the server-side validation logic to the client. You can use the related tag helper to display validation errors on the client.
In the following example form, the asp- tag helper code is as follows:
The tag helper will generate the following source html. Notice that the data- attribute in the HTML output corresponds to the validation property of the ReleaseDate property. The following data-val-required property contains the error message that will be displayed if the user does not fill in the release date field. JQuery non-intrusive validation passes this value to the jQuery Validate required () method, which then displays the error message in the accompanying element.
Movie ReleaseDate
2.4 dynamic form add validation
After you create a dynamic form, you need to analyze it immediately. For example, the following code shows how to set up client-side validation for a form added through AJAX.
Get ({url: "https://url/that/returns/a/form", dataType:" html ", error: function (jqXHR, textStatus, errorThrown) {alert (textStatus +": Couldn't add form.) "+ errorThrown);}, success: function (newFormHTML) {/ / add form newFormHTML var container = document.getElementById (" form-container "); container.insertAdjacentHTML (" beforeend ", newFormHTML); / / verify the first form var forms = container.getElementsByTagName (" form "); var newForm = forms [forms.length-1]; / / analyze the data- property of the form $.validator.unobtrusive.parse (newForm);})
The $.validator.unobtrusive.parse () method parses the data- property of the form in the selector. When the user fills out the attribute values in the form and submits them, the values of those attributes are passed to the jQuery Validate plug-in so that the form shows the required client-side validation rules.
The following is illustrated with a simple example:
(1) create a dynamic-form-validate.js file, simulate the dynamic generation of the form, and verify when you click the (# idbtn) button:
Var newFormHTML = ""; newFormHTML + = ""; newFormHTML + = "; newFormHTML + ="; newFormHTML + = ""; $("# idbtn") .click (function () {var container = document.getElementById ("form-container"); container.insertAdjacentHTML ("beforeend", newFormHTML); var forms = container.getElementsByTagName ("form"); var newForm = forms [forms.length-1] / / analyze the data- property of the form $.validator.unobtrusive.parse (newForm);})
(2) create a new create page
@ model StudyMVCDemo.Models.Movie@ {ViewData ["Title"] = "Create";} Create Back to List@section Scripts {@ {await Html.RenderPartialAsync ("_ ValidationScriptsPartial");}}
To run the program, click "dynamic load form" to call js to add the html form to the form-container element container, and click save to prompt that the field cannot be empty. The effect is as follows:
2.5 dynamic controls add validation
When you dynamically add controls (such as: and) to the form, you need to update the validation rules on the form. You should first delete the existing validation data, and then reanalyze the entire form, as shown in the following js code:
Get ({url: "https://url/that/returns/a/control", dataType:" html ", error: function (jqXHR, textStatus, errorThrown) {alert (textStatus +": Couldn't add control.) "+ errorThrown);}, success: function (newInputHTML) {/ / dynamically add Input controls var form = document.getElementById (" my-form ") to the form; form.insertAdjacentHTML (" beforeend ", newInputHTML); / / remove existing validation $(form) .removeData (" validator ") / / Added by jQuery Validate .removeData (" unobtrusiveValidation ") / / Added by jQuery Unobtrusive Validation / / reanalyze the entire form $.validator.unobtrusive.parse (form);}})
2.6 IClientModelValidator
In the custom validation above, ValidationAttribute is inherited for server-side verification, and client-side verification can be implemented in conjunction with the implementation of the IClientModelValidator interface, which is used to control which data- attributes are added. The implementation interface is as follows:
/ Custom verification / public class ClassicMovieAttribute: ValidationAttribute,IClientModelValidator {private int _ year; / year reference value / public ClassicMovieAttribute (int year) {_ year = year;} protected override ValidationResult IsValid (object value, ValidationContext validationContext) {Movie movie = (Movie) validationContext.ObjectInstance / / users cannot set the genre of movies released after 1960 to Classic if (movie.Genre = = "Classic" & & movie.ReleaseDate.Year > _ year) {return new ValidationResult (GetErrorMessage ());} return ValidationResult.Success;} private string GetErrorMessage () {return $"Classic movies must have a release year earlier than {_ year}." } public void AddValidation (ClientModelValidationContext context) {if (context = = null) {throw new ArgumentNullException (nameof (context));} MergeAttribute (context.Attributes, "data-val", "true"); MergeAttribute (context.Attributes, "data-val-classicmovie", GetErrorMessage ()); var year = _ year.ToString (CultureInfo.InvariantCulture); MergeAttribute (context.Attributes, "data-val-classicmovie-year", year) } private bool MergeAttribute (IDictionary attributes, string key, string value) {if (attributes.ContainsKey (key)) {return false;} attributes.Add (key, value); return true;}}
The generated source html code is as follows:
Although the IClientModelValidator interface is implemented above, jQuery does not know the rules or messages, and needs to customize the classicmovie client authentication method to add to the jQuery validator object. The script is as follows:
/ / add the validation method $.validator.addMethod ('classicmovie',function (value, element, params) {/ / value, which is the value of the currently validated element. / / element element itself. / / params is the passed parameter (options.rules) var genre = $("# form1"). Find ("# Genre") .val (), year = params [0], date = new Date (value); if (genre.length > 0 & & genre = = 'Classic') {/ / Since this is a classic movie, invalid if release date is after given year. Return date.getFullYear ()
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.