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

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

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

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

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

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

  • 怎麼去封裝一個元件?

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

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

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

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

Demo下載

效果預覽

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

Checkbox複選框元件封裝

標籤名稱:cl-checkbox


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

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

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

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

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


1.判斷是否可以多選:


複製程式碼 程式碼如下:

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:綁定單一選項型別為:IEnumerable

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

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中也有,於是也將開關單獨的封裝了一下,代碼大同小異

就這個 

使用也簡單:

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

  }
 }
}
登入後複製

總結

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


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


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


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

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

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

layui登陸頁怎麼設定跳轉 layui登陸頁怎麼設定跳轉 Apr 04, 2024 am 03:12 AM

layui 登入頁面跳轉設定步驟:新增跳轉代碼:在登入表單提交按鈕點選事件中新增判斷,成功登入後透過 window.location.href 跳到指定頁面。修改 form 配置:在 lay-filter="login" 的 form 元素中新增 hidden 輸入字段,name 為 "redirect",value 為目標頁面位址。

layui怎麼取得表單數據 layui怎麼取得表單數據 Apr 04, 2024 am 03:39 AM

layui 提供了多種取得表單資料的方法,包括直接取得表單所有欄位資料、取得單一表單元素值、使用formAPI.getVal() 方法取得指定欄位值、將表單資料序列化並作為AJAX 請求參數,以及監聽表單提交事件獲取資料。

layui跟vue有啥差別 layui跟vue有啥差別 Apr 04, 2024 am 03:54 AM

layui與Vue的差異主要體現在功能和關注點上。 layui專注於快速開發UI元素,提供預製元件簡化頁面建置;而Vue則是全端框架,注重資料綁定、元件化開發和狀態管理,更適合建構複雜應用程式。 layui學習簡單,適合快速建立頁面;Vue學習曲線陡峭,但有助於建立可擴展且易於維護的應用程式。根據專案需求和開發者技能水平,可以選擇合適的框架。

layui如何實現自適應 layui如何實現自適應 Apr 26, 2024 am 03:00 AM

透過使用layui框架的響應式佈局功能,可以實現自適應佈局。步驟包括:引用layui框架。定義自適應佈局容器,設定layui-container類別。使用響應式斷點(xs/sm/md/lg)隱藏特定斷點下的元素。利用網格系統(layui-col-)指定元素寬度。透過偏移量(layui-offset-)建立間距。使用響應式實用工具(layui-invisible/show/block/inline)控制元素的可見性和顯示方式。

layui怎麼傳數據 layui怎麼傳數據 Apr 26, 2024 am 03:39 AM

使用 layui 傳輸資料的方法如下:使用 Ajax:建立請求對象,設定請求參數(URL、方法、資料),處理回應。使用內建方法:使用 $.post、$.get、$.postJSON 或 $.getJSON 等內建方法簡化資料傳輸。

layui是什麼意思啊 layui是什麼意思啊 Apr 04, 2024 am 04:33 AM

layui是一個前端UI框架,它提供了豐富的UI元件、工具和功能,幫助開發人員快速建立現代化、響應式和互動式Web應用程序,特點包括:靈活輕量、模組化設計、豐富的元件、強大的工具和易於自訂。它廣泛應用於各種Web應用程式的開發中,包括管理系統、電商平台、內容管理系統、社交網路和行動裝置應用程式。

layui框架是什麼語言 layui框架是什麼語言 Apr 04, 2024 am 04:39 AM

layui框架是一款基於JavaScript的前端框架,提供了一套易用的UI元件和工具,幫助開發者快速建立響應式網路應用程式。其特點包括:模組化、輕量級、響應式,並擁有完善的文件和社群支援。 layui廣泛應用於管理後台系統、電商網站和行動裝置應用程式等開發。優點在於上手快、提升效率、維護方便,缺點是客製化較差、技術更新較慢。

layui框架和vue框架的區別 layui框架和vue框架的區別 Apr 26, 2024 am 01:27 AM

layui和vue是前端框架,layui是一種輕量級的函式庫,提供UI元件和工具;vue是一個全面的框架,提供UI元件、狀態管理、資料綁定和路由等功能。 layui基於模組化的架構,vue是基於組件化的架構。 layui擁有較小的生態系統,vue擁有龐大且活躍的生態系統。 layui學習曲線較低,vue學習曲線較陡。 layui適用於小型專案和快速開發UI元件,vue適用於大型專案和需要豐富功能的場景。

See all articles