Detailed explanation asp.net Core encapsulation layui component example sharing

Time:2021-4-18

What is the package? It’s just taghelper. What is it? Read the document for yourself

When learning to use taghelper, I hope to have a demo for my reference

  • How to encapsulate a component?
  • How to achieve different situations?
  • Is there a better and more efficient way?

Looking for, looking for, and finally went to see the MVCTagHelpersHave a good lookTaghelper documentation

Reluctantly tossed out a few components, originally wanted to write an article component by component, but found that the National Day has ended~

Demo download

Effect preview

Code for reference only, there are different views also forget to teach

Checkbox component encapsulation

Tag name: CL checkbox

Label property: ASP for: binding field, must be specified

  1. ASP items: the binding single option type is IEnumerable < selectlistitem > 1
  2. asp- skin:layui The default skin style is original
  3. ASP Title: if it is only the text displayed in a check box and items are not specified, the default value of the check box is true

Among them, when we look at the source code, we find two very useful pieces of code

1. Judge whether multiple choices are allowed:

Copy codeThe code is as follows:
var realModelType = For.ModelExplorer.ModelType ; / / judge whether it is multiple-choice var by type_ allowMultiple = typeof(string) != realModelType && typeof(IEnumerable).IsAssignableFrom(realModelType);

2. Get the list value of model binding (in case of multiple choices)

Copy codeThe code is as follows:
var currentValues = Generator.GetCurrentValues(ViewContext,For.ModelExplorer,expression: For.Name,allowMultiple: true);

These three codes are in theThe selecttaghelper of MVCIt was found in the book

In fact, core has provided a lot of taghelpers. For example, the commonly used select is a good reference object. When you encounter problems in encapsulation, you can find it and you will get unexpected results

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>
 ///Check box
 /// </summary>
 /// <remarks>
 ///When items is empty, a single item is displayed, and the value is true after selection
 /// </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 {get; set;} = checkboxskin. Default;

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

  public override void Process(TagHelperContext context, TagHelperOutput output)
  {
   //Gets the generated name property of the binding
   string inputName = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(For?.Name);
   string skin = string.Empty;
   #Region style
   switch (Skin)
   {
    Case checkboxskin. Default:
     skin = "";
     break;
    Case checkboxskin
     skin = "primary";
     break;
   }
   #endregion
   #Region single check box
   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 check box group
   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
 {
  Default,
  original
 }
}

Use examples

@{
String sex = male;
var Items=new List<SelectListItem>()
   {
    New selectlistitem() {text = male, value = male},
    New selectlistitem() {text = female, value = female},
    New selectlistitem() {text = unknown, value = unknown, disabled = true}
   };
}
<cl-checkbox asp-items=" Model.Items "ASP for =" hobby1 "ASP skin =" default "> < / CL checkbox >
< CL checkbox ASP for = hobby3 "ASP title = single check box > < / CL checkbox >

Radio radio box package

Label name: CL radio

  1. Label property: ASP for: binding field, must be specified
  2. ASP items: the binding single option type is IEnumerable < selectlistitem > 1

It’s too simple. It’s code

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>
 ///Radio box
 /// </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 ("model must be bound");
   }
   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 = "";
  }
 }
}

Use examples

@{
String sex = male;
var Items=new List<SelectListItem>()
   {
    New selectlistitem() {text = male, value = male},
    New selectlistitem() {text = female, value = female},
    New selectlistitem() {text = unknown, value = unknown, disabled = true}
   };
}
<cl-radio asp-items="@Items" asp-for="sex"></cl-radio>

Finally, another switch pack

In fact, a single check box can be directly replaced by a switch, which happens to exist in layui, so the switch is encapsulated separately, and the code is similar

That’s it

It is easy to use< CL switch ASP for = "hobby4" ASP switch text = "on | off" > < / CL Switch >

namespace LayuiTagHelper.TagHelpers
{
 /// <summary>
 ///Switch
 /// </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);

  }
 }
}

summary

The package is still very rough, normal use is no problem, if found problems, also hope to point out.

Since layui is a form label rendered directly after the page is loaded, there are not many styles related to layui.

In addition to some form components, it also encapsulates the tab, timeline, pagination and code display components, which will be introduced later.

Of course, those who are interested can take a look at the components

Warehouse address

Wedemo branch clone command:git clone https://git.coding.net/yimocoding/WeDemo.git -b LayuiTagHelper

Tab, timeline, pagination, code display, etcDemo package download

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.