【发布时间】:2021-05-19 02:31:53
【问题描述】:
在 ASP.NET Core MVC Razor 视图中,我有 2 个表单。一个输入表单用于将 2 个下拉列表填充为 ajax modelpopup 并将值保存在数据库中。另一种形式用于在同一视图中将相关值显示为数据表。
当我尝试通过在视图中声明@model IEnumerable<Namespace.Model> 来通过@foreach(var item in Model) 循环填充数据表时,它可以很好地为数据表控件分配值。
但其他具有下拉列表的表单显示错误。无法为选择控件声明 asp-for。
<div class="form-group"> @{var Jsonlist = new electList((System.Collections.IEnumerable)ViewData["JsonPropVD"], "Value", "Key");}
<select asp-items="Jsonlist" asp-for="ClientCatalog" class="form-control"></select>
</div>
public void GetJsonProperties()
{
PropertyInfo[] propertyInfosSM = typeof(SMJsonModel).GetProperties();
if (propertyInfosSM != null)
{
Dictionary<string, object> Jsondictresults = new Dictionary<string, object>();
foreach (PropertyInfo propertyInfoJson in propertyInfosSM)
{
Jsondictresults.Add(propertyInfoJson.Name, propertyInfoJson.Name);
}
ViewBag.VBJsonProp = Jsondictresults.Keys;
ViewData["JsonPropVD"] = Jsondictresults;
}
}
当我从@model IEnumerable<Namespace.Model> 更改为@model<Namespace.Model> 时,我可以访问表单中的下拉列表,但@foreach(var item in Model) 显示错误。所以我需要用 viewbag 填充。
<tbody>
@foreach (K360Master Mappeddata in ViewBag.K360MappedData)
{
<tr>
<td>@Mappeddata.Id</td>
<td>@Mappeddata.ClientCatalog</td>
<td>@Mappeddata.K360catalog</td>
<td>
<button id="btnDelete" asp-action="DeletePost" asp-route-Id="@Mappeddata.Id" class="btn btn-danger mr-3">Delete</button>
</td>
</tr>
}
</tbody>
不建议使用 viewbag 和 viewdata。请指导我如何通过使用强类型视图来满足上述要求。
【问题讨论】:
-
Btw Type.GetProperties 永远不会返回 null。它将返回一个空数组(无属性)或适当大小的数组。所以,总是属性的数量(0 或 N)
标签: c# .net-core razor asp.net-core-mvc