首頁 >後端開發 >C#.Net教程 >asp.net core封裝layui組件的範例詳解

asp.net core封裝layui組件的範例詳解

黄舟
黄舟原創
2017-10-11 10:23:523586瀏覽

本篇文章主要介紹了詳解asp.net core封裝layui組件範例分享,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧

用什麼封裝?這裡只是用了TagHelper,是啥?自己瞅文檔去

在學習使用TagHelper的時候,最希望的就是能有個Demo能夠讓自己作為參考

  • 怎麼去封裝一個元件?

  • 不同的情況怎麼去實作?

  • 有沒有更好更有效率的方法?

找啊找啊找,最後跑去看了看mvc中的TagHelpers,再好好瞅了瞅TagHelper的文檔<br>

##勉強折騰了幾個元件出來,本來想一個元件一個元件寫文章的,但是發現國慶日已經結束了~

Demo下載

效果預覽

程式碼僅供參考,有不同的意見也忘不吝賜教

Checkbox複選框元件封裝<br>

標籤名稱:cl-checkbox

<br>

標籤屬性: asp-for:綁定的字段,必須指定

  1. asp-items:綁定單一選項類型為:IEnumerable90fc9151e669273219504e6e41f84252

  2. asp-skin:layui的皮膚樣式,預設or原始

  3. #asp-title:若只是一個複選框時顯示的文字,且未指定items,預設Checkbox的值為true

#其中在封裝的時候看原始碼發現兩段非常有用的程式碼

<br>

1.判斷是否可以多選:

<br>

複製程式碼 程式碼如下:

var realModelType = For.ModelExplorer.ModelType; //通过类型判断是否为多选 
var _allowMultiple = typeof(string) != realModelType && typeof(IEnumerable).IsAssignableFrom(realModelType);

2.取得模型綁定的清單值(多選的情況)

<br>

複製程式碼 程式碼如下:

var currentValues = Generator.GetCurrentValues(ViewContext,For.ModelExplorer,expression: For.Name,allowMultiple: true);

這3句程式碼是在mvc自帶的SelectTagHelper中發現的.

<br>

因為core其實已經提供了非常多的TagHelper,比如常用的select就是很好的參考對象,封裝遇到問題的時候去找找看指不定就又意外的收穫.

CheckboxTagHelper程式碼

<br>

<br>

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

使用範例

<br>

<br>

@{
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單選框元件封裝<br>

標籤名稱:cl-radio

<br>

  1. #標籤屬性: asp-for:綁定的字段,必須指定

  2. asp-items:綁定單一選項型別為:IEnumerable90fc9151e669273219504e6e41f84252

太簡單了,直接上程式碼了

RadioTagHelper程式碼

<br>

<br>

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

使用範例

<br>

<br>

@{
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>

#最後再來一個開關組件

單一複選框其實可以直接用開關代替,恰巧layui中也有,於是也將開關單獨的封裝了一下,代碼大同小異

就這個 

使用也簡單:

86b8d7165060c94005448b640420d2f0d6e4618ca9b2fd042e132fdca13ef340<br>

<br>

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);

  }
 }
}

總結

#封裝的還很粗糙,正常的使用是沒問題的,若發現問題,還望指出。

<br>

因為layui是直接在頁面載入後渲染的表單標籤,故沒有太多和layui相關的樣式。

<br>

除了一些表單元件之外,其實還對選項卡,時間軸,分頁,程式碼顯示元件做了一些封裝,這些後面再介紹了。

<br>

當然,有興趣的朋友可以先去一睹為快看看都實現了哪些元件

以上是asp.net core封裝layui組件的範例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn