TagHelper+Layui封裝組件之Radio單選框


TagHelper+Layui封裝組件之Radio單選框

  • 標簽名稱:cl-radio
  • 標簽屬性:
    • asp-for:綁定的字段,必須指定
    • asp-items:綁定單選項 類型為:IEnumerable<SelectListItem>
      太簡單了,直接上代碼了

RadioTagHelper代碼

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

使用示例

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM