c#-Blazor 动态字段和带有验证/验证器的 ASP.Net.Core
发布时间:2022-07-06 03:54:31 276
相关标签: # flask
我试图编写一个Blazor应用程序(从服务器端开始),通过验证动态创建其表单字段。我喜欢Razor附带的绑定到模型的验证/验证器,但我不知道如何对动态创建的字段(也称为无模型)进行验证。
这就是我所拥有的。我非常感谢您的指导。
Startup.cs
...
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton();
}
...
ControlTypes.cs
namespace DynamicContent
{
public enum ControlTypes
{
Text = 1,
Date = 2,
DateTime = 3,
Time = 4,
SingleSelect = 5, // DropdownList
MultiSelect = 6,
Boolean = 7, // Checkbox or Slide
Email = 8,
RadioButtonList = 9
}
}
ControlDetails.cs
namespace DynamicContent
{
public class ControlDetails
{
public string ID { get; set; }
public string FieldName { get; set; }
public ControlTypes Type { get; set; } = ControlTypes.Text;
public string Label { get; set; }
public bool IsRequired { get; set; }
public bool IsReadOnly { get; set; } = false;
public string Tooltip { get; set; } // ToDo: Default to Label (if not set)
public string Placeholder { get; set; }
public string Min { get; set; } = string.Empty;
public string Max { get; set; } = string.Empty;
}
}
DynamicControlService.cs
using System.Collections.Generic;
namespace DynamicContent
{
public class DynamicControlService
{
public List GetControls()
{
// Eventually this will pull from a database
var result = new List();
result.Add(new ControlDetails { FieldName = "firstName", Label = "First Name", IsRequired = true });
result.Add(new ControlDetails { FieldName = "lastName", Label = "Last Name", IsRequired = true });
result.Add(new ControlDetails { FieldName = "birthDate", Type = ControlTypes.Date, Label = "Birth Date",
IsRequired = false, Tooltip = "Please enter Birth Date in mm/dd/yyyy format" });
return result;
}
}
}
Counter.razor
@page "/counter"
@inject DynamicControlService _controlService
<form>
@foreach (var control in ControlList)
{
<div class="form-group">
<!-- Label -->
<label asp-for=@(control.FieldName) class="label-control">
@(control.Label) @if (control.IsRequired)
{<b> *</b>}
</label>
<!-- Input field -->
@switch (control.Type)
{
case ControlTypes.Text:
<input type="text" id="@control.ID" class="form-control" asp-for=@(control.FieldName)
@bind-value="@Values[control.Label]" required="@control.IsRequired" />
break;
case ControlTypes.Email:
<input type="email" id="@control.ID" class="form-control" value="@Values[control.Label]"
required="@control.IsRequired" />
break;
case ControlTypes.Date:
<input type="date" id="@control.ID" class="form-control" value="@Values[control.Label]"
required="@control.IsRequired" @onchange="@(a => ValueChanged(a, control.Label))"
min="1900-01-01" max="2999-12-31"/>
break;
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报