Making an ASP.NET 6 MVC connecting to SQL server through EF where you pick an option using a Dropdownlist from the Incident class when creating a Transaction classobject thus binding them together. However an Incident is often active during a limited time window so they all have a Incident.IsActive boolean(managed in another view and works). The Dropdownlist itself works but I want to limit it to only showing active Incidents if(Incident.IsActive). The real issue is that I dont fully understand the syntax to manipulate the object I get back from the DB through EF.
Transaction controller has this method for Creating a new transaction, here if would like to add something akin to if(Incident.isActive) display it in this SelectList
public TransactionController(MyAppDbContext context)
{
_context = context;
}
public IActionResult Create()
{
//display the dropdownlist, here I assume you would iterate through it and only pick IsActive
ViewBag.Incident = new SelectList(_context.Incidents.ToList(), "IncidentId", "IncidentName");
return View();
}
Assume that the logic should be dealt with in the Transaction controller but this is how it's displayed in the Transaction/Create view.
<div >
<label asp-for="Incident.IncidentId" ></label>
<select asp-for="Incident.IncidentId" asp-items="@ViewBag.Incident" >
<option>Pick an incident</option>
</select>
<span asp-validation-for="Incident.IncidentId" ></span>
</div>
Might not be relevant but here is also the Transaction/Create Post method.
// POST: Transactions/Create
[HttpPost]
public async Task<IActionResult> Create([FromForm] Transaction transaction)
{
ModelState.Remove("Incident.IncidentName");
if (ModelState.IsValid)
{
transaction.Incident = _context.Incidents.Find(transaction.Incident.IncidentId);
_context.Add(transaction);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewBag.Incident = new SelectList(_context.Incidents.ToList(), "IncidentId", "IncidentName");
return View(transaction);
}
CodePudding user response:
The Dropdownlist itself works but I want to limit it to only showing active Incidents if(Incident.IsActive).
The easiest way to show the active Incidents is to add a where clause to filter the data when query the Incidents from the database (using _context). The query statement like this:
ViewBag.Incident = new SelectList(_context.Incidents.Where(c => c.isActive == true).ToList(), "IncidentId", "IncidentName");
Before adding the where
clause, the result will contain the active or inactive Incidents:
After adding the where
clause, the result only contains the active options:
[Note] Both in the Get and Post methods, you should add the where
clause in query statement.
Here are some relates articles about LINQ query operations, you can refer to them: