How to Count number of items in model using IEnumerable<T>

34,088

Solution 1

You can just use @Model.Count() to display count anywhere – (credit goes to @MukeshModhvadiya from the comment section)

Solution 2

You are use Model.Count() inside View for MVC. If you need it in javascript you can get this value in following way:

<script type="text/javascript">
var count ='@Model.Count()';
</script>

You have to write script in View file. separate js file this code not working. We are not able to access Model value in separate js file.

Share:
34,088
Matchbox2093
Author by

Matchbox2093

"Every day you learn something new" "There is no stupid questions, except for the one not asked"

Updated on February 05, 2020

Comments

  • Matchbox2093
    Matchbox2093 about 4 years

    I was wondering is it possible to do a counter for the number of items in a model, i know using list it is possible, but id prefer to use IEnumerable for the project purpose. it would be even better if it could be done in javascript for constant update but im not experienced enough in MVC and Javascript.

    -Controller-

    public class ModelController : Controller
    {
        private JobData db = new JobData();
    
        //
        // GET: /Model/
    
        public ActionResult Index()
        {
            var Model = db.Models.OrderByDescending(model => model.ModelType);
            int count = Model.Count();
    
            return View(Model.ToList());
        }
    

    -View-

        @model IEnumerable<JobTracker.Models.Model>
    
    @{
        ViewBag.Title = "Camera Models";
    }
    
     <script type="text/javascript" src="~/Scripts/Table.js"></script>
    
    
    
    
    <table id="tfhover" class="tftable" border="1">  
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ModelType)
            </th>
            <th></th>
        </tr>
    
    @foreach (var item in Model) {
    
    
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ModelType)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ModelID }) |
                @Html.ActionLink("Details", "Details", new { id=item.ModelID }) 
              @*  @Html.ActionLink("Delete", "Delete", new { id=item.ModelID })*@
            </td>
        </tr>
    }
    
    </table>
    
  • Just Fair
    Just Fair over 5 years
    this counts only the model not its references ie: inside a for loop.