asp.net mvc-c#mvc模型绑定嵌套列表

本文关键字:嵌套 列表 绑定 模型 net mvc-c#mvc asp | 更新日期: 2023-09-27 17:58:51

我的模型绑定出现问题。这里有以下型号:

public class RoomScan
{
    public RoomScan() { }
    public RoomScan(Guid id)
    {
        Room_ID = id;
        Assets = new List<AssetScanModel>();
    }
    //public Guid Soll_ID { get; set; }
    public Guid Room_ID { get; set; }
    public List<AssetScanModel> Assets { get; set; }
    [Display(Name = "Barcode", ResourceType = typeof(Dictionary))]
    public string Barcode { get; set; }
    [Display(Name = "RFID", ResourceType = typeof(Dictionary))]
    public string RFID { get; set; }
}
public class AssetScanModel
{
    public AssetScanModel(Asset asset)
    {
        Asset = asset;
        Scanned = false;
        CheckIn = false;
    }
    public Asset Asset { get; set; }
    [Display(Name = "Scanned", ResourceType = typeof(Dictionary))]
    public bool Scanned { get; set; }
    [Display(Name = "CheckIn", ResourceType = typeof(Dictionary))]
    public bool CheckIn { get; set; }
}

视图确实列出了所有资产:

using (Html.BeginForm("Scan", "Inventory", FormMethod.Post))
{
Html.HiddenFor(rs => rs.Room_ID);
Html.HiddenFor(rs => rs.Assets);
<div>
    <div class="editor-label">Barcode</div>
    <div class="editor-field"><input type="text" name="Barcode" value="@Model.Barcode" /></div>
</div>
<div>
    <div class="editor-label">RFID</div>
    <div class="editor-field"><input type="text" name="Barcode" value="@Model.RFID" /></div>
</div><br />

@for (int i = 0; i < Model.Assets.Count; i++)
{
    <tr>
        <td>@Html.DisplayFor(asm => asm.Assets[i].Asset.InventoryNumber)</td>
        <td>@Html.DisplayFor(asm => asm.Assets[i].Asset.Description)</td>
        <td>@Html.DisplayFor(asm => asm.Assets[i].Asset.Manufacturer)</td>
        <td>@Html.DisplayFor(asm => asm.Assets[i].Asset.Model)</td>
        <td>@Html.DisplayFor(asm => asm.Assets[i].Asset.SerialNumber)</td>
        <td>@Html.DisplayFor(asm => asm.Assets[i].Scanned)</td>
        <td>@Html.DisplayFor(asm => asm.Assets[i].CheckIn)</td>
    </tr>
}

我添加了"Asset[I]",因为我在某个地方读到它有助于默认模型绑定器正确绑定(不起作用)

我的问题是:在我的控制器中:

[HttpPost]
    public ActionResult Scan(RoomScan toVerify)

列表为空(不是null)。我知道这与模型活页夹有关,但我不熟悉如何更改它,所以它确实有效。

asp.net mvc-c#mvc模型绑定嵌套列表

我一直在使用它来绑定具有嵌套列表的复杂模型。我几乎总是用这个替换默认的模型活页夹。。。

可以更新复杂模型图的DefaultModelBinder

我希望这对你和我一样有帮助。

尝试DisplayTemplates/EditorTemplates,为您的嵌套模型类型创建模板。在视图中写入:

@Html.DisplayFor(asm => asm.Assets)

在DisplayTemplate(AssetScanModel.cs.html)中:

@model AssetScanModel
<tr>
    <td>@Html.DisplayFor(asm => asm.Asset.InventoryNumber)</td>
    <td>@Html.DisplayFor(asm => asm.Asset.Description)</td>
    <td>@Html.DisplayFor(asm => asm.Asset.Manufacturer)</td>
    <td>@Html.DisplayFor(asm => asm.Asset.Model)</td>
    <td>@Html.DisplayFor(asm => asm.Asset.SerialNumber)</td>
    <td>@Html.DisplayFor(asm => asm.Scanned)</td>
    <td>@Html.DisplayFor(asm => asm.CheckIn)</td>
</tr>