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" >
<option selected disabled>--choose supplier--</option>
</select>
<button type="submit" >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);
CodePudding user response:
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");