You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC:编辑Devices时读取Contact关联数据问题

需求:在设备创建/编辑视图中显示联系人全名列表

我已配置好数据模型的外键关系,清楚数据库层面的关联逻辑,但不知道如何在ASP.NET中实现——希望在Devices的创建和编辑视图里,通过Entity Framework显示contact.full_name的列表供选择。以下是我的相关代码:

DBContext代码

entity.ToTable("DeviceAssignments", "Assets");

entity.Property(e => e.AssignDate).HasColumnType("date");
entity.Property(e => e.Created)
            .HasDefaultValueSql("(getdate())")
            .HasColumnType("datetime");
entity.Property(e => e.Creator)
            .IsRequired()
            .HasMaxLength(150)
            .IsUnicode(false)
            .HasDefaultValueSql("(suser_sname())");
entity.Property(e => e.Modified)
            .HasDefaultValueSql("(getdate())")
            .HasColumnType("datetime");
entity.Property(e => e.Modifier)
            .IsRequired()
            .HasMaxLength(150)
            .IsUnicode(false)
            .HasDefaultValueSql("(suser_sname())");
entity.Property(e => e.ReturnDate).HasColumnType("date");

entity.HasOne(d => d.Contact).WithMany(p => p.DeviceAssignments)
            .HasForeignKey(d => d.ContactID)
            .OnDelete(DeleteBehavior.ClientSetNull)
            .HasConstraintName("FK_DeviceAssignments_Contact");

entity.HasOne(d => d.Device).WithMany(p => p.DeviceAssignments)
            .HasForeignKey(d => d.DeviceId)
            .OnDelete(DeleteBehavior.ClientSetNull)
            .HasConstraintName("FK_DeviceAssignments_Devices");


entity.ToTable("Devices", "Assets");

entity.Property(e => e.Comment)
            .HasMaxLength(150)
            .IsUnicode(false);
entity.Property(e => e.Cost).HasColumnType("decimal(9, 4)");
entity.Property(e => e.Created)
            .HasDefaultValueSql("(getdate())")
            .HasColumnType("datetime");
entity.Property(e => e.Creator)
            .IsRequired()
            .HasMaxLength(150)
            .IsUnicode(false)
            .HasDefaultValueSql("(suser_sname())");
entity.Property(e => e.Description)
            .HasMaxLength(150)
            .IsUnicode(false);
entity.Property(e => e.InvoiceNumber)
            .HasMaxLength(50)
            .IsUnicode(false);
entity.Property(e => e.MAC)
            .HasMaxLength(50)
            .IsUnicode(false);
entity.Property(e => e.Model)
            .HasMaxLength(150)
            .IsUnicode(false);
entity.Property(e => e.Modified)
            .HasDefaultValueSql("(getdate())")
            .HasColumnType("datetime");
entity.Property(e => e.Modifier)
            .IsRequired()
            .HasMaxLength(150)
            .IsUnicode(false)
            .HasDefaultValueSql("(suser_sname())");
entity.Property(e => e.PurchaseDate).HasColumnType("date");
entity.Property(e => e.SerialNumber)
            .HasMaxLength(50)
            .IsUnicode(false);
entity.Property(e => e.Status)
            .HasMaxLength(50)
            .IsUnicode(false);

entity.HasOne(d => d.DeviceCategory).WithMany(p => p.Devices)
            .HasForeignKey(d => d.DeviceCategoryId)
            .OnDelete(DeleteBehavior.ClientSetNull)
            .HasConstraintName("FK_Devices_DeviceCategories");

entity.HasOne(d => d.DeviceLocation).WithMany(p => p.Devices)
            .HasForeignKey(d => d.DeviceLocationId)
            .HasConstraintName("FK_Devices_DeviceLocations");

DevicesController代码(Edit方法)

// GET: Devices/Edit/5
public async Task<IActionResult> Edit(int? id)
{
    if (id == null || _context.Devices == null)
    {
        return NotFound();
    }

    var devices = await _context.Devices.FindAsync(id);

    if (devices == null)
    {
        return NotFound();
    }

    ViewData["DeviceCategoryId"] = new SelectList(_context.DeviceCategories, "DeviceCategoryId", "DeviceCategoryName", devices.DeviceCategoryId);
    ViewData["DeviceLocationId"] = new SelectList(_context.DeviceLocations, "DeviceLocationId", "DeviceLocationName", devices.DeviceLocationId);            

    return View(devices);
}

Edit.cshtml代码

@model QsccDevAlpha.Models.Devices

@{
    ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<h4>Devices</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="DeviceId" />
            <div class="form-group">
                <label asp-for="DeviceCategoryId" class="control-label"></label>
                <select asp-for="DeviceCategoryId" class="form-control" asp-items="ViewBag.DeviceCategoryId"></select>
                <span asp-validation-for="DeviceCategoryId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DeviceLocationId" class="control-label"></label>
                <select asp-for="DeviceLocationId" class="form-control" asp-items="ViewBag.DeviceLocationId"></select>
                <span asp-validation-for="DeviceLocationId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SerialNumber" class="control-label"></label>
                <input asp-for="SerialNumber" class="form-control" />
                <span asp-validation-for="SerialNumber" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PurchaseDate" class="control-label"></label>
                <input asp-for="PurchaseDate" asp-format="{0:MM/dd/yyyy}" class="form-control" />
                <span asp-validation-for="PurchaseDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="InvoiceNumber" class="control-label"></label>
                <input asp-for="InvoiceNumber" class="form-control" />
                <span asp-validation-for="InvoiceNumber" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="MAC" class="control-label"></label>
                <input asp-for="MAC" class="form-control" />
                <span asp-validation-for="MAC" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Model" class="control-label"></label>
                <input asp-for="Model" class="form-control" />
                <span asp-validation-for="Model" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Status" class="control-label"></label>
                <input asp-for="Status" class="form-control" />
                <span asp-validation-for="Status" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Cost" class="control-label"></label>
                <input asp-for="Cost" class="form-control" />
                <span asp-validation-for="Cost" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Comment" class="control-label"></label>
                <input asp-for="Comment" class="form-control" />
                <span asp-validation-for="Comment" class="text-danger"></span>
            </div>            
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

实现步骤

1. 传递联系人列表到视图(控制器端)

在Edit和Create方法中,添加联系人列表的ViewData赋值逻辑:

// 假设联系人实体主键为ContactId,全名属性为FullName
ViewData["ContactId"] = new SelectList(_context.Contacts, "ContactId", "FullName");

修改后的Edit方法示例:

// GET: Devices/Edit/5
public async Task<IActionResult> Edit(int? id)
{
    if (id == null || _context.Devices == null)
    {
        return NotFound();
    }

    var devices = await _context.Devices.FindAsync(id);

    if (devices == null)
    {
        return NotFound();
    }

    ViewData["DeviceCategoryId"] = new SelectList(_context.DeviceCategories, "DeviceCategoryId", "DeviceCategoryName", devices.DeviceCategoryId);
    ViewData["DeviceLocationId"] = new SelectList(_context.DeviceLocations, "DeviceLocationId", "DeviceLocationName", devices.DeviceLocationId);            
    // 添加联系人列表
    ViewData["ContactId"] = new SelectList(_context.Contacts, "ContactId", "FullName");

    return View(devices);
}

2. 在视图中添加联系人选择控件

在Edit.cshtml的表单内插入下拉选择框,位置可按需调整:

<div class="form-group">
    <label asp-for="ContactId" class="control-label">联系人</label>
    <select asp-for="ContactId" class="form-control" asp-items="ViewBag.ContactId">
        <option value="">请选择联系人</option>
    </select>
    <span asp-validation-for="ContactId" class="text-danger"></span>
</div>

3. 多对多关联的特殊处理

从DBContext代码可知,Device和Contact通过DeviceAssignments中间表实现多对多关联,若需给设备绑定多个联系人,建议:

  • 创建ViewModel,包含Device实体和List<int> SelectedContactIds属性
  • 视图中使用多选控件绑定该属性
  • POST方法中根据选中的联系人ID,更新DeviceAssignments表的关联数据

内容的提问来源于stack exchange,提问作者tjestesjr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 06:57:04