.net core使用Ku.Core.Extensions.Layui實現layui表單渲染


演示網站地址:http://layui.kulend.com/
項目地址:https://github.com/kulend/Ku.Core.Extensions/tree/master/Ku.Core.Extensions.Layui

Demo代碼:https://github.com/kulend/Ku.Core.Extensions/tree/master/Tests/Ku.Core.Extensions.Layui.Test


如果您的.net core 2.0項目使用layui來渲染表單,那么您可以嘗試使用這個HtmlHelper擴展來幫你減少代碼和工作量。

安裝方法
PM> Install-Package Ku.Core.Extensions.Layui -Version 2.2.0.0
dotnet add package Ku.Core.Extensions.Layui --version 2.2.0.0

使用方法:
1.在Startup的ConfigureServices方法中

//使用Layui
services.AddLayui();

 

2._ViewImports.cshtml文件中添加

@addTagHelper *, Ku.Core.Extensions.Layui

 

3.定義Model及其屬性,例如:

public class DemoModel
{
    /// <summary>
    /// ID
    /// </summary>
    [DataType("hidden")]
    public long Id { get; set; }

    /// <summary>
    /// 名稱
    /// </summary>
    [Required, MaxLength(20), MinLength(5)]
    [Display(Name = "名稱", Description = "附加說明文字")]
    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "輸入的名稱不符合規則")]
    public string Name { get; set; }

    /// <summary>
    /// 名稱
    /// </summary>
    [Required]
    [Display(Name = "手機號")]
    [DataType(DataType.PhoneNumber)] //也可以為[DataType("mobile")]
    public string Mobile { get; set; }

    /// <summary>
    /// 鏈接
    /// </summary>
    [MaxLength(256)]
    [Display(Name = "鏈接")]
    [DataType(DataType.Url)]
    public string Url { get; set; }

    /// <summary>
    /// Email
    /// </summary>
    [MaxLength(256)]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    /// <summary>
    /// 序號
    /// </summary>
    [Display(Name = "序號", Prompt ="0~9999")]
    public int OrderIndex { get; set; } = 0;

    /// <summary>
    /// 序號
    /// </summary>
    [Display(Name = "數字", Prompt = "0~9999")]
    [Range(-1, 999.05)]
    public decimal Dec { get; set; } = 0;

    /// <summary>
    /// 開關
    /// </summary>
    [Display(Name = "開關", Prompt = "開|關")]
    public bool Switch { get; set; } = true;

    [Display(Name = "時間")]
    [DisplayFormat(DataFormatString = "yyyy-MM-dd HH:mm:ss")] //定義顯示格式
    [DataType(DataType.DateTime)] //也可以這樣[DataType("datetime")]
    public DateTime? Date { set; get; }

    [Display(Name = "年份")]
    [DataType("year")]
    public int Year { set; get; }

    [Display(Name = "月份")]
    [DisplayFormat(DataFormatString = "現在是yyyy年MM月")]
    [DataType("month")]
    public string Month { set; get; }

    /// <summary>
    /// 枚舉
    /// </summary>
    [Display(Name = "性別")]
    public EmSex Sex { set; get; }

    /// <summary>
    /// 多行文本
    /// </summary>
    [Display(Name = "備注", Prompt = "請輸入您的備注信息...")]
    [MaxLength(500)]
    [DataType(DataType.MultilineText)] //或者[DataType("textarea")]
    public string Remark { set; get; }
}

/// <summary>
/// 性別
/// </summary>
public enum EmSex : short
{
    [Display(Name = "保密")]
    Secret = 0,

    [Display(Name = "")]
    Male = 1,

    [Display(Name = "")]
    Female = 2
}

 

4.在form中使用@Html.InputFor,如

            @using (Html.BeginForm<DemoModel>("#"))
            {
                @Html.InputFor(x => x.Id)
                @Html.InputFor(x => x.Name, x => x.Mobile)
                @Html.InputFor(x => x.Url, x => x.Email)
                @Html.InputFor(x => x.OrderIndex, x => x.Dec)
                @Html.InputFor(x => x.Sex)
                @Html.InputFor(x => x.Switch, x => x.Date)
                @Html.InputFor(x => x.Year, x => x.Month)
                @Html.InputFor(x => x.Remark)
                @Html.ActionsForSubmitAndReset()
            }

或者使用@Html.ShowFor,如

            @using (Html.BeginForm<DemoModel>("#"))
            {
                @Html.InputFor(x => x.Id)
                @Html.ShowFor(x => x.Name, x => x.Mobile)
                @Html.ShowFor(x => x.Url, x => x.Email)
                @Html.ShowFor(x => x.OrderIndex, x => x.Dec)
                @Html.ShowFor(x => x.Sex)
                @Html.ShowFor(x => x.Switch, x => x.Date)
                @Html.ShowFor(x => x.Year, x => x.Month)
                @Html.ShowFor(x => x.Remark)
            }

使用ShowFor需要在頁面添加以下css代碼:

<style>
    .layui-form-item .layui-form-label-show {
        float: left;
        display: block;
        padding: 9px 15px;
        font-weight: 400;
        text-align: left;
        color: #808080;
    }

    .layui-form-item .layui-input-block .layui-form-label-show {
        width: 85%;
    }
</style>

來個效果圖:

 

show

怎么樣,很簡單吧。

通過設置字段的DataType和各種ValidationAttribute特性還可以完成表單數據驗證,如:

[Required]:不能為空
[MaxLength]特性:最大長度驗證 
[MinLength]特性:最小長度驗證 
[StringLength]特性:最大和最小長度驗證
[DataType(DataType.PhoneNumber)]或[DataType("mobile")]:手機號驗證 
[DataType(DataType.Url)]:網址驗證 
[DataType(DataType.EmailAddress)]或[DataType("email")]:Email驗證 
字段類型為int:整數驗證 
字段類型為decimal:數字驗證 
[RegularExpression]特性:自定義正則表達式驗證,如[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "輸入的名稱不符合規則")]

 

注意:表單驗證功能需擴展layui的驗證,可下載form.verify.js
https://github.com/kulend/Ku.Core.Extensions/blob/master/Tests/Ku.Core.Extensions.Layui.Test/wwwroot/js/form.verify.js

5.其他說明:
1)bool型字段默認會渲染成switch,lay-text需要這樣設置:

[Display(Name = "開關", Prompt = "開|關")]

 

2)除了字段類型,很多時候需要DataTypeAttribute來判斷渲染方式,默認為text,還可設置hidden,password,multilinetext,textarea,datetime,date,year,month,time等。multilinetext和textarea會渲染成Textarea。
3)關於Action按鈕,

@Html.ActionsForSubmit(), 添加保存按鈕(提交表單)。 
@Html.ActionsForSubmitAndClose(), 添加保存和關閉按鈕。 
@Html.ActionsForSubmitAndReset(), 添加保存和重置按鈕。 
@Html.ActionsFor(btns), 添加自定義按鈕,例如:
@Html.ActionsFor(
new SubmitButton(),
new CloseButton(),
new ResetButton { Text = "重置表單" },
new ActionButton { Id = "btn_test", Text = "自定義按鈕", Css = "btn-test", OnClick = "alert(1);" }
)

 

4)修改全局默認配置

//使用Layui
services.AddLayui(opt => {
opt.ActionsInFormItem = false;
opt.ActionTagTheme = "layui-btn-primary";
opt.ActionTagSize = "layui-btn-sm";
});

 

5)關於laydate組件,需要在頁面添加以下js腳本:

layui.use(['laydate'], function () {
    var $ = layui.jquery
    , laydate = layui.laydate;

    $(".layui-input.laydate").each(function () {
        var self = $(this);
        var type = self.data("type") || 'date';
        var format = self.data("format") || 'yyyy-MM-dd';
        laydate.render({
            elem: self[0],
            type: type,
            format: format
        });
    });
});

 

項目在不斷更新,如有bug或其他建議,可以提交issue。也可郵件給我:kulend@qq.com


免責聲明!

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



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