如何从控制器 ASP.NET MVC 的视图页面中自动添加所选 ID 的名称

How to automatically add a name from selected id in View page from controller ASP.NET MVC

我想从我的视图页面中选择的 id 中获取一个名字

第一个模型

public class Transaction
{
    [Key]
    public int Id { get; set; }
    [Required]
    public int supplier_id { get; set; }
    [Required]
    public string supplier_name { get; set; }
}

第二个模型

public class Supplier
{
    [Key]
    public int supplier_id { get; set; }
    [Required]
    public string supplier_name { get; set; }
}

查看模型

public class EvaluateSheet
{
    public IEnumerable<Supplier> Suppliers{ get; set; }
    public IEnumerable<Transaction> Transactions { get; set; }
    public Transaction Transaction { get; set; }
}

控制器

public IActionResult Sheet11()
    
    {
        var sup = _db.Supplier.ToList();
        ViewBag.Sup = new SelectList(sup, "supplier_id", "supplier_name");
        return View();
    }
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Sheet11(EvaluateSheet objc)
    {
           Transaction Model = objc.Transaction;
           Transaction transaction = new Transaction();
           transaction.Id = Model.Id;
           transaction.supplier_id = Model.supplier_id;
           transaction.supplier_name = Model.supplier_name;
           _db.Transaction.Add(Model);
           Model.supplier_name = Model.Supplier.supplier_name.Where(Model.Supplier.supplier_id == Model.supplier_id);
           _db.SaveChanges();
           return RedirectToAction("Index");
    }

查看页面

@model EvaluateSheet 
<form method="post">
<select asp-for="@Model.Transaction.supplier_id" asp-items="@ViewBag.Sup" value="@ViewBag.Sup" class="form-control">
                    <option selected disabled>--choose supplier--</option>
</select>
<button type="submit" class="btn btn-primary">Add Transaction</button>

我想在我的视图页面中选择 supplier_id 后自动将 supplier_name 字段插入到数据库中。 我已经在我的控制器中试过了,但它不起作用

Model.supplier_name = Model.Supplier.supplier_name.Where(Model.Supplier.supplier_id == Model.supplier_id);

试试这个:

EvaluateSheet模型中为example("public int Sup_id { get; set; }")定义一个整型变量,并用DropDownListFor标记。

在控制器 select 中来自供应商 table 的特定数据借助新定义 int Sup_id 并将此数据复制到 Model(Transaction).

例如:

Transaction Model = new Transaction();
            Supplier supl = null;
            supl = _db.Supplier.Where(x => x.supplier_id == objc.Sup_id).FirstOrDefault();
            Model.supplier_id = supl.supplier_id;
            Model.supplier_name = supl.supplier_name;
            _db.Transaction.Add(Model);
            _db.SaveChanges();
            return RedirectToAction("Index");