I have a question how to solve my problem. There is a table with items. Each item has a status "open" or "closed". For instance, 9 items with "closed" status and 14 ones with "open". I need to find the difference between open and closed items (14 - 9 = 5
). How can I do it with help of ViewBag
? As I understood, it is required to write "count" function in controller and transmit the result to View via ViewBag
. But I don’t know how to write this code. The result should be shown on the View page.
Request.cs (Model):
public class Request
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string Status { get; set; } = "";
}
Controller.cs:
public IActionResult Requests()
{
var Requests = _repo.GetAllRequests();
return View(Requests);
}
Repository:
public Request GetRequest(int id)
{
return _ctx.Requests.FirstOrDefault(c => c.Id == id);
}
public List<Request> GetAllRequests()
{
return _ctx.Requests.ToList();
}
View:
<div>
<table>
@foreach (var request in Model)
{
<tr>
<th>@request.Name</th>
<th>@request.Status</th>
</tr>
}
</table>
</div>
2
Answers
You would pass a predicate to
Count
to filter the requests by status:However, rather than using the
ViewBag
you could create a view model to hold all the information/data required by the view:Also, I suggest you; Do not use status fields as strings. It will be easier for you if you keep it as an enum.