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

I want to get a name from selected id in my view page

First Model

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

Second Model

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

View Model

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

Controller

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");
    }

View Page

@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>

I want to automatically insert supplier_name field after I selected supplier_id in my View page into the database. I have tried this in my controller but it doesn't work

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


Solution 1:[1]

Try this:

Define an integer type variable in EvaluateSheet model for example("public int Sup_id { get; set; }") and tag it with DropDownListFor.

In Controller select specific data from supplier table with the help of new define int Sup_id and copy this data in Model(Transaction).

For example:

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");
        

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tasos K.