借助 ViewBag 的 Count 和 Sum 函数

Count and Sum functions with help of ViewBag

我想知道如何解决我的问题。有一个 table 与项目。每个项目的状态为“打开”或“关闭”。例如,9 个项目的状态为“关闭”,14 个项目的状态为“开放”。我需要找到打开和关闭项目之间的区别 (14 - 9 = 5)。我该如何在 ViewBag 的帮助下完成?据我了解,需要在控制器中编写“计数”功能并将结果通过ViewBag传输到View。但我不知道如何编写这段代码。结果应显示在“查看”页面上。

Request.cs(型号):

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

存储库:

public Request GetRequest(int id)
{
    return _ctx.Requests.FirstOrDefault(c => c.Id == id);
}

public List<Request> GetAllRequests()
{
    return _ctx.Requests.ToList();
}

查看:

<div>
    <table>
        @foreach (var request in Model)
        {
        <tr>
            <th>@request.Name</th>
            <th>@request.Status</th>
        </tr>
        }
    </table>
</div>

您可以将谓词传递给 Count 以按状态过滤请求:

public IActionResult Requests()
{
    var requests = _repo.GetAllRequests();

    ViewBag.OpenRequests = requests.Count(r => r.Status == "open");
    ViewBag.ClosedRequests = requests.Count(r => r.Status == "closed");

    return View(requests);
}

但是,您可以创建一个视图模型来保存视图所需的所有 information/data,而不是使用 ViewBag

// ViewModel
public class RequestViewModel
{
    public List<Request> Requests { get; set; }
    public int OpenRequests { get; set; }
    public int ClosedRequests { get; set; }
}

// Controller
public IActionResult Requests()
{
    var requests = _repo.GetAllRequests();
    
    var viewModel = new RequestViewModel();
    viewModel.OpenRequests = requests.Count(r => r.Status == "open");
    viewModel.ClosedRequests = requests.Count(r => r.Status == "closed");
    viewModel.Requests = requests;

    return View(viewModel);
}

// View: set the model for the view
@model Project.Namespace.RequestViewModel
...
<div>
    <div>Open Requests: @model.OpenRequests</div>
    <div>Closed Requests: @model.ClosedRequests</div>
    <div>Difference/delta: @(model.OpenRequests - model.ClosedRequests)</div>
</div>
    private StatisticScore()
    {
        var openCount =_ctx.Requests.Where(m=> m.Status == "Open").Count();
       var closedCount = _ctx.Requests.Where(m=> m.Status == "Closed").Count();
        ViewBag.Difference  = openCount  - closedCount 
    }

  <label> Difference </label> @ViewBag.Difference 

另外,我建议你;不要将状态字段用作字符串。如果将其保留为枚举,对您来说会更容易。