[SOLVED] ASP.NET MVC – Show counts using razor view in foreach

Issue

Below is my razor code

for (int i = 0; i < Model.physicians.Count; i++)
{ 
    <div>
        @Model.physicians[i].npi -- Count: 
    </div>
}

I have table npipatients as below:

npiId Patientname
1 a
1 b
2 c

My output like this in razor view

1 — Count:2

2 — Count:1

I need to write ajax call but how to pass npiid to ajax method for foreach and assign result of npi count to label.

$.ajax({
    type: "POST",
    url: "/mycontroler/GetnpiDetails",
    dataType: "json",
    data: { "npiId": npiId },                    
    success: function (data) {


   }
});

Solution

From what I understand based on your question (Please correct me if I’m wrong), looks like you are trying to fire the API with each Npi record for getting the (grouping) count.

In my perspective, it is NOT EFFICIENT, imagine there are 100 records and you will call the API 100 times. This will lead to pulling down your server performance (Handling the same task 100 times) and also database server (Query the same data 100 times).

Instead,

You need to do the data transformation in Controller first by .GroupBy() the npi record and .Count() for each grouped record.

Expected output:

[
  { "npi": 1, "count": 2 },
  { "npi": 2, "count": 1 }
]

With 1 single API call saves you the performance from calling m time as discussed.

What’s you need to do:

  1. Model – Design your desired output with the model class.
  2. Controller – Perform data transformation: Grouping by npiId.
  3. View – Bind the value from Controller.

Model

public class GroupedNpiModel
{
    public int NpiId { get; set; }

    public int Count { get; set; }
}

Controller

public ActionResult Index()
{
    var data = new []
    {
        new { NpiId = 1, Patientname = "a" } ,
        new { NpiId = 1, Patientname = "b" } ,
        new { NpiId = 2, Patientname = "c" } 
    };
            
    var groupedNpi = data.GroupBy(x => x.NpiId)
        .Select(g => new GroupedNpiModel
        {
            NpiId = g.Key,
            Count = g.Count()
        })
        .ToList();
        
    return View(groupedNpi);
}

View

@model IEnumerable<HelloWorldMvcApp.GroupedNpiModel>

@foreach (var npi in Model)
{
    <div>
        @npi.NpiId -- @npi.Count
    </div>
}

Sample program on .NET Fiddle

Answered By – Yong Shun

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *