ASP.NET Core MVC from entry to proficiency in Html auxiliary label supplement and model verification basis

With the development of technology, ASP.NET Core MVC has also been launched for a long time. After continuous version update iterations, it has become more and more perfect. This series of articles mainly explains the related content involved in the process of ASP.NET Core MVC development B/S system. It is suitable for beginners, school graduates, or other personnel who want to engage in ASP.NET Core MVC system development.

After the explanations of the previous articles, I have a preliminary understanding of ASP.NET Core MVC project creation, startup and operation, and naming conventions, creating controllers, views, models, receiving parameters, passing data ViewData, ViewBag, routing, page layout, wwwroot and client libraries, Razor syntax, EnityFrameworkCore and databases, HttpContext, Request, Response, Session, serialization, file upload, automatic mapping, Html auxiliary tags, etc. Today, I will continue to explain H in ASP.NET Core MVC The second part of the tml auxiliary tag and the basics of model verification and other related content are only for learning and sharing .

In the previous article, I explained the ActionLink, Label, Text, RadioButton, CheckBox, TextArea, Password, Form and other tags of auxiliary tags. Today, I will continue to explain the second part on the basis of the previous article.

Drop-down box DropDownList and multi-select list box ListBox

1. Drop-down box

The drop-down box is mainly used to display multiple information for users to choose. It is mainly used for single selection. It is mainly represented by @Html.DropDownList. There are 6 overloads in total. The parameters are as follows:

  1. expression: expression name, generally used to represent the name of the text box.
  2. selectList: The data source of the drop-down list, IEnumerable<SelectListItem> type, generally implemented with SelectList.
  3. optionLabel: the text displayed by default
  4. htmlAttributes: Hyperlink Html attributes, such as: style, class, width, height, etc., can receive anonymous objects.

dropdown box example

First prepare the data source, usually obtained from the database, as follows:

List<City> cityList = new List<City>
{
    new City() { Id = 1, Name = "北京" },
    new City() { Id = 2, Name = "上海" },
    new City() { Id = 3, Name = "广州" },
    new City() { Id = 4, Name = "深圳" }
};
var citys = new SelectList(cityList, "Id", "Name");
ViewBag.Citys = citys;

Among them, SelectList is the implementation class of IEnumerable<SelectListItem>, pass in the list, and specify the value and text.

@Html.Label("City","城市",new { style="width:90px;"})
@Html.DropDownList("City", ViewBag.Citys,"请选择",new {style="width:120px;"})

2. Multiple choice list

The multi-choice list box is mainly used to display multiple information for users to choose. It is generally used for multi-choice. It is mainly represented by @Html.ListBox. There are 3 overloads. The parameters are as follows:

  1. expression: expression name, generally used to represent the name of the text box.
  2. selectList: The data source of the drop-down list, IEnumerable<SelectListItem> type, generally implemented with SelectList.
  3. htmlAttributes: Hyperlink Html attributes, such as: style, class, width, height, etc., can receive anonymous objects.

Example of a multi-select list box

@Html.Label("MultiCity","多选城市",new { style="width:90px;vertical-align:top;"})
@Html.ListBox("MultiCity", ViewBag.Citys,new {style="width:120px;"})

3. Html native code for drop-down box and multi-select box

The drop-down box and list box in the above example, the corresponding native Html code is as follows:

<label for="City" style="width:90px;">城市</label>
<select id="City" name="City" style="width:120px;">
    <option value="">请选择</option>
    <option value="1">北京</option>
    <option value="2">上海</option>
    <option value="3">广州</option>
    <option value="4">深圳</option>
</select>
<br>
<br>
<label for="MultiCity" style="width:90px;vertical-align:top;">多选城市</label>
<select id="MultiCity" multiple="multiple" name="MultiCity" style="width:120px;">
    <option value="1">北京</option>
    <option value="2">上海</option>
    <option value="3">广州</option>
    <option value="4">深圳</option>
</select>

Html escape

Sometimes, the content in a specific format will be output, but it will be escaped when outputting in C#, so that the desired effect cannot be achieved. In this case, the @Html.Raw method needs to be used. A total of 2 overloads, the main parameters are as follows:

  1. value: It needs to be the output content, there are two types: string and TModel.

@Html.Raw example

@Html.Raw("<font color='red'>大家好,这是测试Raw输出</font>")

The above method will output native Html<font color='red'>Hi everyone, this is the test Raw output</font>, and the red text content will be displayed on the page. Instead of outputting the escaped content.

model checking

In actual application development, we always need to write a lot of verification. This is unavoidable. If you don’t write it, you will not be safe. If you write it, it will be very cumbersome. For a robust application, not only the front-end but also the back-end need to write verification to prevent illegal data intrusion.

The process of implementing verification can be tedious, but it is essential. In MVC, validation happens on the client and the server. Fortunately, .NET has abstracted validation into validation properties. These properties contain validation code, reducing the amount of code that needs to be written.

Rules that expose data about the app by reading the entire model, making code maintenance easier. Here are a few commonly used built-in validation properties:

  • [CreditCard]: Validates that the attribute has a credit card format.

  • [Compare]: Validates that two attributes in a model match.

  • [EmailAddress]: Validates that the attribute has an email format.

  • [Phone]: Validates that the attribute has a phone format.

  • [Range]: Validates that an attribute value falls within a given range.

  • [RegularExpression]: Verify that the data matches the specified regular expression.

  • [Required]: Sets the attribute as required.

  • [StringLength]: Validates that a string property has at most the given maximum length.

  • [Url]: Validates that the attribute has URL format.

Model Validation Steps

1. Add validation features to the model

Add validation features to the model, as follows:

using System.ComponentModel.DataAnnotations;

namespace DemoCoreMVC.Models
{
    public class User
    {
        [Required(ErrorMessage ="Id不能为空")]
        [Range(0, 100,ErrorMessage ="Id必须的0到100之内")]
        public int Id { get; set; }

        [Required(ErrorMessage ="用户名称不能为空")]
        public string Name { get; set; }

        [Required(ErrorMessage ="邮箱不可为空")]
        [EmailAddress(ErrorMessage ="邮件不符合格式")]
        public string Email { get; set; }
    }
}

2. Introduce verification partial view

Add the introduction of the verification script in the View view, as follows:

<!--Edit.cshtml文件的底部增加以下引入部分视图-->
@section Scripts{
    @(await Html.PartialAsync("_ValidationScriptsPartial"))
}

3. Add verification information label

Where Edit.cshtml needs to display validation information, add @Html.ValidationMessageFor information display, as shown below:

@using (Html.BeginForm("Save","User",FormMethod.Post))
{
    @Html.Label("Id","User Id",new { style="width:90px;"});
    @Html.TextBox("Id",Model.Id)
    @Html.ValidationMessageFor(p=>p.Id)
    <br />
    <br />
    @Html.Label("Name","User Name",new { style="width:90px;"})
    @Html.TextBox("Name",Model.Name)
    @Html.ValidationMessageFor(p=>p.Name)
    <br />
    <br />
    @Html.Label("Email","E-Mail",new { style="width:90px;"})
    @Html.TextBox("Email",Model.Email)
    @Html.ValidationMessageFor(p=>p.Email)
    <br />
    <br />
    <input type="submit" value="保存" class="btn btn-primary" />
}

4. Model verification effect

The model verification effect is as follows:

Note: After testing, if the model validation is to take effect, the Expression between @Html.TextBox, @Html.Label, @Html.ValidationMessageFor must be consistent, otherwise it will not take effect.

The above is the whole content of ASP.NET Core MVC from entry to proficiency, supplementary label supplement and model verification basis.

Guess you like

Origin blog.csdn.net/fengershishe/article/details/131137065