search
HomeBackend DevelopmentC#.Net TutorialDetailed example of asp.net core encapsulating layui component

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);
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);
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
 {
  默认,
  原始
 }
}

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>


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 = "";
  }
 }
}

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>

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:

<br><pre class='brush:php;toolbar:false;'>namespace LayuiTagHelper.TagHelpers { /// &lt;summary&gt; /// 开关 /// &lt;/summary&gt; [HtmlTargetElement(SwitchTagName)] public class SwitchTagHelper : TagHelper { private const string SwitchTagName = &quot;cl-switch&quot;; private const string ForAttributeName = &quot;asp-for&quot;; private const string SwitchTextAttributeName = &quot;asp-switch-text&quot;; 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; } = &quot;ON|OFF&quot;; public override void Process(TagHelperContext context, TagHelperOutput output) { string inputName = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(For?.Name); output.TagName = &quot;input&quot;; output.TagMode = TagMode.SelfClosing; if (For?.Model?.ToString().ToLower() == &quot;true&quot;) { output.Attributes.Add(&quot;checked&quot;, &quot;checked&quot;); } output.Attributes.Add(&quot;type&quot;, &quot;checkbox&quot;); output.Attributes.Add(&quot;id&quot;, inputName); output.Attributes.Add(&quot;name&quot;, inputName); output.Attributes.Add(&quot;value&quot;, &quot;true&quot;); output.Attributes.Add(&quot;lay-skin&quot;, &quot;switch&quot;); output.Attributes.Add(&quot;lay-text&quot;, SwitchText); } } }</pre>

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
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
2023最新layui视频教程推荐(建议收藏)2023最新layui视频教程推荐(建议收藏)Jul 19, 2021 pm 05:22 PM

以下为大家整理了前端UI框架 — layui的视频教程,不需要从迅雷、百度云之类的第三方网盘平台下载,全部在线免费观看。教程由浅入深,有前端基础的人就能学习,从安装到案例讲解,全面详细,帮助你更快更好的掌握layui框架!

如何利用Layui开发一个具有分页功能的数据展示页面如何利用Layui开发一个具有分页功能的数据展示页面Oct 24, 2023 pm 01:10 PM

如何利用Layui开发一个具有分页功能的数据展示页面Layui是一个轻量级的前端UI框架,提供了简洁美观的界面组件和丰富的交互体验。在开发中,我们经常会遇到需要展示大量数据并进行分页的情况。以下是一个利用Layui开发的具有分页功能的数据展示页面的示例。首先,我们需要引入Layui的相关文件和依赖。在html页面的&lt;head&gt;标签中加入以下代

如何利用Layui实现图片轮播图功能如何利用Layui实现图片轮播图功能Oct 24, 2023 am 08:27 AM

如何利用Layui实现图片轮播图功能现如今,图片轮播图已经成为了网页设计中常见的元素之一。它可以使网页更加生动活泼,吸引用户的眼球,提升用户体验。在本文中,我们将介绍如何利用Layui框架来实现一个简单的图片轮播图功能。首先,我们需要在HTML页面中引入Layui的核心文件和样式文件:&lt;linkrel=&quot;stylesheet&quot;h

如何利用Layui实现图片拖拽和缩放效果如何利用Layui实现图片拖拽和缩放效果Oct 24, 2023 am 09:16 AM

如何利用Layui实现图片拖拽和缩放效果在现代网页设计中,图片的交互效果成为增加网页活力和用户体验的重要手段。其中,图片拖拽和缩放效果是常见且受欢迎的交互方式之一。本文将介绍如何使用Layui框架实现图片拖拽和缩放效果,并提供具体的代码示例。一、引入Layui框架和相关依赖:首先,我们需要在HTML文件中引入Layui框架和相关依赖。可以通过以下代码示例引入

如何使用Layui开发一个支持图片放大缩小的相册功能如何使用Layui开发一个支持图片放大缩小的相册功能Oct 24, 2023 am 09:02 AM

如何使用Layui开发一个支持图片放大缩小的相册功能相册功能在现代的网页应用中非常常见,通过展示用户上传的图片,让用户能够方便地浏览和管理图片。为了提供更好的用户体验,一种常见的需求是支持图片的放大和缩小功能。本文章将介绍如何使用Layui框架开发一个支持图片放大缩小的相册功能,同时提供具体的代码示例。首先,确保您已经引入Layui框架的CSS和JS文件。您

如何利用Layui实现图片反色和亮度调节功能如何利用Layui实现图片反色和亮度调节功能Oct 25, 2023 am 09:10 AM

如何利用Layui实现图片反色和亮度调节功能引言:在前端开发中,经常会遇到需要对图片进行特效处理的情况。本文将介绍如何利用Layui框架实现图片反色和亮度调节功能,并提供具体代码实例供参考。一、Layui简介:Layui是一款优秀的前端UI框架,具有简洁、美观、易用等特点。它提供了丰富的前端组件,让开发者能够轻松搭建出精美的网站。二、准备工作:在开始之前,我

如何使用Layui开发一个支持文件上传和下载的资源管理系统如何使用Layui开发一个支持文件上传和下载的资源管理系统Oct 24, 2023 am 09:19 AM

如何使用Layui开发一个支持文件上传和下载的资源管理系统引言:随着互联网的发展,数据资源的管理已经成为一项重要的任务。无论是企业内部的文档管理,还是个人的文件存储,都需要一个高效且易于使用的资源管理系统。Layui是一款轻量级的前端框架,具有简洁明了的设计以及丰富的组件库,非常适合用来进行资源管理系统的开发。本文将介绍如何使用Layui开发一个支持文

如何使用Layui框架开发一个支持实时通讯的在线客服系统如何使用Layui框架开发一个支持实时通讯的在线客服系统Oct 25, 2023 am 08:47 AM

如何使用Layui框架开发一个支持实时通讯的在线客服系统概述:在线客服系统是现代企业提供与客户交流的重要渠道之一,而实时通讯是在线客服系统的关键技术之一。本文将介绍如何使用Layui框架开发一个支持实时通讯的在线客服系统,并提供具体的代码示例。一、准备工作安装Node.js:在开发环境中安装Node.js,并配置好相关环境。安装Layui:在项目中引入Lay

See all articles

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 Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.