使 ASP.NET 6 MVC 通過 EF 連接到 SQL Server,您可以在創建 Transaction 類物件時使用 Incident 類中的 Dropdownlist 選擇一個選項,從而將它們系結在一起。但是,事件通常在有限的時間視窗內處于活動狀態,因此它們都有一個 Incident.IsActive 布林值(在另一個視圖中管理并有效)。Dropdownlist 本身可以作業,但我想將其限制為僅顯示活動事件 if(Incident.IsActive)。真正的問題是我不完全理解通過 EF 操作從資料庫回傳的物件的語法。
事務控制器有這個創建新事務的方法,在這里如果想添加類似于 if(Incident.isActive) 的東西在這個 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();
}
假設邏輯應該在 Transaction 控制器中處理,但這就是它在 Transaction/Create 視圖中的顯示方式。
<div class="form-group">
<label asp-for="Incident.IncidentId" class="control-label"></label>
<select asp-for="Incident.IncidentId" asp-items="@ViewBag.Incident" class="form-control">
<option>Pick an incident</option>
</select>
<span asp-validation-for="Incident.IncidentId" class="text-danger"></span>
</div>
可能不相關,但這里也是 Transaction/Create Post 方法。
// 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);
}
uj5u.com熱心網友回復:
Dropdownlist 本身可以作業,但我想將其限制為僅顯示活動事件 if(Incident.IsActive)。
顯示活動事件的最簡單方法是添加 where 子句以在從資料庫中查詢事件時過濾資料(使用 _context)。查詢陳述句如下:
ViewBag.Incident = new SelectList(_context.Incidents.Where(c => c.isActive == true).ToList(), "IncidentId", "IncidentName");
在添加where子句之前,結果將包含活動或非活動事件:

添加where子句后,結果只包含活動選項:
[注意] Get 和 Post 方法都需要where在查詢陳述句中添加子句。

這里有一些關于 LINQ 查詢操作的相關文章,您可以參考它們:
基本 LINQ 查詢操作
where 子句(C# 參考)
LINQ 運算子和 Lambda 運算式 - 語法和示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516919.html
標籤:网asp.net 核心下拉式菜单实体框架 6
上一篇:在不顯式管理HttpClient的情況下為多個Refit端點重用Polly重試策略
下一篇:將Id從視圖決議到控制器
