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

ASP.NET中Create视图外键下拉框实现简易教程求助

ASP.NET Create视图外键下拉框实现步骤

以下是最简实现方案,以**商品(Product)关联分类(Category)**为例:

1. 定义实体模型

// 主表:分类
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// 子表:商品,外键关联分类
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    // 外键字段
    public int CategoryId { get; set; }
    // 导航属性(可选,用于EF关联查询)
    public Category Category { get; set; }
}

2. 配置数据库上下文

确保DbContext中注册实体:

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

3. 控制器代码(推荐用ViewModel)

ViewModel用于封装视图所需数据,避免直接传递实体:

// 视图模型
public class ProductCreateVm
{
    public string ProductName { get; set; }
    // 绑定选中的分类ID
    public int SelectedCategoryId { get; set; }
    // 下拉框选项列表
    public IEnumerable<SelectListItem> CategoryOptions { get; set; }
}

// Products控制器
public class ProductsController : Controller
{
    private readonly AppDbContext _db;

    public ProductsController(AppDbContext db) => _db = db;

    // GET: 打开创建页面
    public IActionResult Create()
    {
        var vm = new ProductCreateVm
        {
            // 从数据库拉取分类数据,转换为下拉框选项
            CategoryOptions = _db.Categories.Select(c => new SelectListItem
            {
                Value = c.Id.ToString(),
                Text = c.Name
            })
        };
        return View(vm);
    }

    // POST: 提交创建表单
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(ProductCreateVm vm)
    {
        if (!ModelState.IsValid)
        {
            // 验证失败时重新加载下拉框选项
            vm.CategoryOptions = _db.Categories.Select(c => new SelectListItem
            {
                Value = c.Id.ToString(),
                Text = c.Name
            });
            return View(vm);
        }

        // 转换为实体并保存
        var product = new Product
        {
            Name = vm.ProductName,
            CategoryId = vm.SelectedCategoryId
        };
        _db.Products.Add(product);
        await _db.SaveChangesAsync();

        return RedirectToAction(nameof(Index));
    }
}

4. Create视图代码(Create.cshtml)

@model ProductCreateVm

<h1>新增商品</h1>

<form asp-action="Create">
    <div class="form-group">
        <label>商品名称</label>
        <input asp-for="ProductName" class="form-control" />
        <span asp-validation-for="ProductName" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label>所属分类</label>
        <!-- 绑定下拉框选项和选中值 -->
        <select asp-for="SelectedCategoryId" asp-items="@Model.CategoryOptions" class="form-control">
            <option value="">-- 请选择分类 --</option>
        </select>
        <span asp-validation-for="SelectedCategoryId" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">保存</button>
</form>

<div>
    <a asp-action="Index">返回列表</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

简化方案(不用ViewModel)

如果不想写ViewModel,可直接用ViewBag传递下拉框选项:

  • 控制器GET方法:
public IActionResult Create()
{
    ViewBag.CategoryList = new SelectList(_db.Categories, "Id", "Name");
    return View();
}
  • 视图中:
<select asp-for="CategoryId" asp-items="@ViewBag.CategoryList" class="form-control">
    <option value="">-- 请选择分类 --</option>
</select>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:28:10