What is the use of model.Count in MVC 4

Posted by Swappy_Gaj under ASP.NET MVC on 1/19/2015 | Points: 10 | Views : 13019 | Status : [Member] | Replies : 1
It going through my head what exactly is the use of Model.Count() in MVC 4

Please help me to understand the difference between the foreach() loop and for loop using Model.Count() in MVC




Responses

Posted by: Sheonarayan on: 1/19/2015 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Model.Count() will be only useful in case you have the @model specified as collection or IEnumerable as asked in one of your question.

For loop can loop through any number of times provided you have specified 2nd condition and perform any operation no necessarily on which object count you are looping through.

@for (int i = 0; i < Model.Count(); i++)
{

}

foreach loop is only useful when you have similar types of object in the collection. For example, you may loop through string collection or integer collection or a class collection. Foreach loop gives you ability to access the object in each iteration without using any indexer, like
@foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.PropertyName)
}

Here, we are able to access each item (object of the collection) of the Model (ie. collection of the class) and access its property.





Regards,
Sheo Narayan
http://www.dotnetfunda.com

Swappy_Gaj, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response