[英]How to generate id and name attribute input form and model dynamically using Entity-Attribute-Value EAV?
我需要為我的數據庫設計使用實體屬性值 (EAV) 方法。 這些是我的模型。
public class TableMetadataTemplate
{
public Guid Id { get; set; }
public string? TableName { get; set; }
public string? FieldName { get; set; }
public string? FieldType { get; set; }
public string? FieldLabel { get; set; }
public int Sequence { get; set; }
public bool Required { get; set; }
public string? DefalutValue { get; set; }
}
public class TableMetadata
{
public Guid Id { get; set; }
public Guid TableMetadataTemplateId { get; set; }
public Guid RecordId { get; set; }
public string? FieldValue { get; set; }
}
這是表中的示例數據:
我正在使用 Razor 頁,這是我創建表單的代碼:
@foreach (var row in Model.TableMetadataTemplate)
{
var fieldType = row.FieldType;
switch (fieldType)
{
case "TEXT":
<div class="form-group">
<label for="@fieldName" class="control-label">@fieldLabel</label>
<input type="text" asp-for="@row.FieldName" class="form-control" value="">
<span asp-validation-for="@fieldName" class="text-danger"></span>
</div>
break;
}
}
注:以上僅為一例。
但是,當我檢查文本框屬性時,它不會生成我需要的正確 id 和 name 屬性值。
<input type="text" id="row_FieldName" name="row.FieldName" value="">
我需要的正確 id 和 name 屬性值如下所示:
<input type="text" id="TableMetadataTemplate_application_name" name="TableMetadataTemplate.application_name" value="">
根據您的描述,您似乎想將該值綁定到后端。 但是這里的ApplicationName
是您的屬性FieldName
的實際值。
您需要知道 model 綁定按名稱屬性綁定屬性。 也就是說name屬性的值應該和屬性名匹配。
Model.TableMetadataTemplate
是一個 List model 類型。 如果要將值發布到此類型屬性,則需要設置唯一名稱,例如: ModelName[index].propertyname
無論您的 foreach 循環包含一個還是多個記錄。
頁:
@page
@model IndexModel
<form method="post">
@for (int i=0;i< Model.TableMetadataTemplate.Count();i++)
{
<div class="form-group">
<input type="text" asp-for="@Model.TableMetadataTemplate[i].FieldName" class="form-control" value="">
</div>
}
<input type="submit" value="Post"/>
</form>
后端:
public class IndexModel : PageModel
{
//you can see the value here when form submit...
[BindProperty]
public List<TableMetadataTemplate> TableMetadataTemplate { get; set; }
public async Task OnGet()
{
// be sure set the data value here, otherwise `Model.TableMetadataTemplate` in page will get null exception...
TableMetadataTemplate =xxx
}
public void OnPost()
{
//do your stuff...
}
}
2.如果你不
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.