Home Backend Development C#.Net Tutorial Detailed example of asp.net core encapsulating layui component

Detailed example of asp.net core encapsulating layui component

Oct 11, 2017 am 10:23 AM
asp.net core layui

This article mainly introduces the detailed explanation of the asp.net core encapsulated layui component example sharing. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

What package should I use? TagHelper is just used here, what is it? Read the documentation yourself

When learning to use TagHelper, what I hope most is to have a Demo that I can use as a reference

  • How to encapsulate a component?

  • How to implement different situations?

  • Is there a better and more efficient way?

I searched and searched, and finally ran to look at TagHelpers in mvc, and then took a good look at TagHelper’s documentation

I barely struggled for a while After each component came out, I originally wanted to write an article one by one, but I found that the National Day is over~

Demo download

Effect preview

##The code is for reference only, please feel free to enlighten me if you have different opinions

Checkbox checkbox component package

Tag name: cl-checkbox


Tag attributes: asp-for: The bound field must be specified

    ##asp-items: The binding single option type is: IEnumerable
  1. asp-skin: Layui skin style, default or original
  2. asp-title: If it is just a check box, the text displayed, and Items are not specified, and the default Checkbox value is true

When looking at the source code during encapsulation, I found two very useful pieces of code


1. Determine whether multiple selections are possible:


Copy code

The code is as follows:

var realModelType = For.ModelExplorer.ModelType; //通过类型判断是否为多选 
var _allowMultiple = typeof(string) != realModelType && typeof(IEnumerable).IsAssignableFrom(realModelType);
Copy after login
2. Get the list value of model binding ( Multiple selection)


Copy code

The code is as follows:

var currentValues = Generator.GetCurrentValues(ViewContext,For.ModelExplorer,expression: For.Name,allowMultiple: true);
Copy after login
These three lines of code were found in the SelectTagHelper that comes with mvc.


Because core has actually provided a lot of TagHelpers. For example, the commonly used select is a good reference object. When you encounter problems with the encapsulation, you may find unexpected results if you look for them.

CheckboxTagHelper code


using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace LayuiTagHelper.TagHelpers
{
 /// <summary>
 /// 复选框
 /// </summary>
 /// <remarks>
 /// 当Items为空时显示单个,且选择后值为true
 /// </remarks>
 [HtmlTargetElement(CheckboxTagName)]
 public class CheckboxTagHelper : TagHelper
 {
  private const string CheckboxTagName = "cl-checkbox";
  private const string ForAttributeName = "asp-for";
  private const string ItemsAttributeName = "asp-items";
  private const string SkinAttributeName = "asp-skin";
  private const string SignleTitleAttributeName = "asp-title";
  protected IHtmlGenerator Generator { get; }
  public CheckboxTagHelper(IHtmlGenerator generator)
  {
   Generator = generator;
  }

  [ViewContext]
  public ViewContext ViewContext { get; set; }

  [HtmlAttributeName(ForAttributeName)]
  public ModelExpression For { get; set; }

  [HtmlAttributeName(ItemsAttributeName)]
  public IEnumerable<SelectListItem> Items { get; set; }

  [HtmlAttributeName(SkinAttributeName)]
  public CheckboxSkin Skin { get; set; } = CheckboxSkin.默认;

  [HtmlAttributeName(SignleTitleAttributeName)]
  public string SignleTitle { get; set; }

  public override void Process(TagHelperContext context, TagHelperOutput output)
  {
   //获取绑定的生成的Name属性
   string inputName = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(For?.Name);
   string skin = string.Empty;
   #region 风格
   switch (Skin)
   {
    case CheckboxSkin.默认:
     skin = "";
     break;
    case CheckboxSkin.原始:
     skin = "primary";
     break;
   }
   #endregion
   #region 单个复选框
   if (Items == null)
   {
    output.TagName = "input";
    output.TagMode = TagMode.SelfClosing;
    output.Attributes.Add("type", "checkbox");
    output.Attributes.Add("id", inputName);
    output.Attributes.Add("name", inputName);
    output.Attributes.Add("lay-skin", skin);
    output.Attributes.Add("title", SignleTitle);
    output.Attributes.Add("value", "true");
    if (For?.Model?.ToString().ToLower() == "true")
    {
     output.Attributes.Add("checked", "checked");
    }
    return;
   }
   #endregion
   #region 复选框组
   var currentValues = Generator.GetCurrentValues(ViewContext,For.ModelExplorer,expression: For.Name,allowMultiple: true);
   foreach (var item in Items)
   {
    var checkbox = new TagBuilder("input");
    checkbox.TagRenderMode = TagRenderMode.SelfClosing;
    checkbox.Attributes["type"] = "checkbox";
    checkbox.Attributes["id"] = inputName;
    checkbox.Attributes["name"] = inputName;
    checkbox.Attributes["lay-skin"] = skin;
    checkbox.Attributes["title"] = item.Text;
    checkbox.Attributes["value"] = item.Value;
    if (item.Disabled)
    {
     checkbox.Attributes.Add("disabled", "disabled");
    }
    if (item.Selected || (currentValues != null && currentValues.Contains(item.Value)))
    {
     checkbox.Attributes.Add("checked", "checked");
    }

    output.Content.AppendHtml(checkbox);
   }
   output.TagName = "";
   #endregion
  }
 }
 public enum CheckboxSkin
 {
  默认,
  原始
 }
}
Copy after login

Usage example


##
@{
string sex="男";
var Items=new List<SelectListItem>()
   {
    new SelectListItem() { Text = "男", Value = "男" },
    new SelectListItem() { Text = "女", Value = "女"},
    new SelectListItem() { Text = "不详", Value = "不详",Disabled=true }
   };
}
<cl-checkbox asp-items="Model.Items" asp-for="Hobby1" asp-skin="默认"></cl-checkbox>
<cl-checkbox asp-for="Hobby3" asp-title="单个复选框"></cl-checkbox>
Copy after login


Radio radio selection Box component encapsulation


Tag name: cl-radio


##Tag attribute: asp-for: bound field, must be specified

  1. asp-items: The binding single option type is: IEnumerable

  2. It’s too simple, just add the code

  3. RadioTagHelper code


using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace LayuiTagHelper.TagHelpers
{
 /// <summary>
 /// 单选框
 /// </summary>
 [HtmlTargetElement(RadioTagName)]
 public class RadioTagHelper : TagHelper
 {
  private const string RadioTagName = "cl-radio";
  private const string ForAttributeName = "asp-for";
  private const string ItemsAttributeName = "asp-items";

  [ViewContext]
  public ViewContext ViewContext { get; set; }

  [HtmlAttributeName(ForAttributeName)]
  public ModelExpression For { get; set; }

  [HtmlAttributeName(ItemsAttributeName)]
  public IEnumerable<SelectListItem> Items { get; set; }

  public override void Process(TagHelperContext context, TagHelperOutput output)
  {
   if (For == null)
   {
    throw new ArgumentException("必须绑定模型");
   }
   foreach (var item in Items)
   {
    var radio = new TagBuilder("input");
    radio.TagRenderMode = TagRenderMode.SelfClosing;
    radio.Attributes.Add("id", ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(For.Name));
    radio.Attributes.Add("name", ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(For.Name));
    radio.Attributes.Add("value", item.Value);
    radio.Attributes.Add("title", item.Text);
    radio.Attributes.Add("type", "radio");
    if (item.Disabled)
    {
     radio.Attributes.Add("disabled", "disabled");
    }
    if (item.Selected || item.Value == For.Model?.ToString())
    {
     radio.Attributes.Add("checked", "checked");
    }
    output.Content.AppendHtml(radio);
   }
   output.TagName = "";
  }
 }
}
Copy after login

Usage example


##

@{
string sex="男";
var Items=new List<SelectListItem>()
   {
    new SelectListItem() { Text = "男", Value = "男" },
    new SelectListItem() { Text = "女", Value = "女"},
    new SelectListItem() { Text = "不详", Value = "不详",Disabled=true }
   };
}
<cl-radio asp-items="@Items" asp-for="sex"></cl-radio>
Copy after login

Finally come back A switch component


In fact, a single check box can be directly replaced by a switch. It happens to be available in layui, so the switch is also encapsulated separately. The code is similar

That’s it

Easy to use:


namespace LayuiTagHelper.TagHelpers
{
 /// <summary>
 /// 开关
 /// </summary>
 [HtmlTargetElement(SwitchTagName)]
 public class SwitchTagHelper : TagHelper
 {
  private const string SwitchTagName = "cl-switch";
  private const string ForAttributeName = "asp-for";
  private const string SwitchTextAttributeName = "asp-switch-text";

  protected IHtmlGenerator Generator { get; }
  public SwitchTagHelper(IHtmlGenerator generator)
  {
   Generator = generator;
  }

  [ViewContext]
  public ViewContext ViewContext { get; set; }

  [HtmlAttributeName(ForAttributeName)]
  public ModelExpression For { get; set; }

  [HtmlAttributeName(SwitchTextAttributeName)]
  public string SwitchText { get; set; } = "ON|OFF";

  public override void Process(TagHelperContext context, TagHelperOutput output)
  {
   string inputName = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(For?.Name);
   output.TagName = "input";
   output.TagMode = TagMode.SelfClosing;
   if (For?.Model?.ToString().ToLower() == "true")
   {
    output.Attributes.Add("checked", "checked");
   }
   output.Attributes.Add("type", "checkbox");
   output.Attributes.Add("id", inputName);
   output.Attributes.Add("name", inputName);
   output.Attributes.Add("value", "true");
   output.Attributes.Add("lay-skin", "switch");
   output.Attributes.Add("lay-text", SwitchText);

  }
 }
}
Copy after login

Summary


The packaging is still very rough. Normal use is no problem. If any problems are found, please contact us. Hope pointed out.

Because layui is a form tag that is rendered directly after the page is loaded, there are not many styles related to layui.


In addition to some form components, it actually also encapsulates tabs, timelines, paging, and code display components, which will be introduced later.


Of course, interested friends can take a quick look at what components have been implemented

The above is the detailed content of Detailed example of asp.net core encapsulating layui component. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get form data in layui How to get form data in layui Apr 04, 2024 am 03:39 AM

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

How to set up jump on layui login page How to set up jump on layui login page Apr 04, 2024 am 03:12 AM

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

How layui implements self-adaptation How layui implements self-adaptation Apr 26, 2024 am 03:00 AM

Adaptive layout can be achieved by using the responsive layout function of the layui framework. The steps include: referencing the layui framework. Define an adaptive layout container and set the layui-container class. Use responsive breakpoints (xs/sm/md/lg) to hide elements under specific breakpoints. Specify element width using the grid system (layui-col-). Create spacing via offset (layui-offset-). Use responsive utilities (layui-invisible/show/block/inline) to control the visibility of elements and how they appear.

What is the difference between layui and vue? What is the difference between layui and vue? Apr 04, 2024 am 03:54 AM

The difference between layui and Vue is mainly reflected in functions and concerns. Layui focuses on rapid development of UI elements and provides prefabricated components to simplify page construction; Vue is a full-stack framework that focuses on data binding, component development and state management, and is more suitable for building complex applications. Layui is easy to learn and suitable for quickly building pages; Vue has a steep learning curve but helps build scalable and easy-to-maintain applications. Depending on the project needs and developer skill level, the appropriate framework can be selected.

How to run layui How to run layui Apr 04, 2024 am 03:42 AM

To run layui, perform the following steps: 1. Import layui script; 2. Initialize layui; 3. Use layui components; 4. Import layui styles (optional); 5. Ensure script compatibility and pay attention to other considerations. With these steps, you can build web applications using the power of layui.

What language is layui framework? What language is layui framework? Apr 04, 2024 am 04:39 AM

The layui framework is a JavaScript-based front-end framework that provides a set of easy-to-use UI components and tools to help developers quickly build responsive web applications. Its features include: modular, lightweight, responsive, and has complete documentation and community support. layui is widely used in the development of management backend systems, e-commerce websites, and mobile applications. The advantages are quick start-up, improved efficiency, and easy maintenance. The disadvantages are poor customization and slow technology updates.

Which one is better, layui or elementui? Which one is better, layui or elementui? Apr 04, 2024 am 04:15 AM

Question: Which one is better, layui or ElementUI? Answer: It depends on the project requirements. Layui is more comprehensive, customizable and suitable for large projects, while ElementUI is more lightweight, beautiful and easy to use. The specific reasons for selection are as follows: Choose layui: Provides a wider range of functions and modules that allow a high degree of customization of component appearance and behavior. Suitable for large projects that require a wide range of functions and scalability. Choose ElementUI: Smaller size and faster loading speed. Components follow Material Design principles. , high aesthetics, providing a large number of ready-made components, reducing development complexity and time

The difference between layui framework and vue framework The difference between layui framework and vue framework Apr 26, 2024 am 01:27 AM

layui and vue are front-end frameworks. layui is a lightweight library that provides UI components and tools; vue is a comprehensive framework that provides UI components, state management, data binding, routing and other functions. layui is based on a modular architecture, and vue is based on a componentized architecture. layui has a smaller ecosystem, vue has a large and active ecosystem. The learning curve of layui is low, and the learning curve of vue is steep. Layui is suitable for small projects and rapid development of UI components, while vue is suitable for large projects and scenarios that require rich functions.

See all articles