0

In my project I have got an actionResult method returning a collection of objects like this:

public ActionResult PartNumberManufacturer(string id)
{
    var partNumber = Context.PartNumberTable.Where(x => x.PartNumberId == id); 
    return PartialView("PartNumberView",    partNumber);
}

This is my View

@model IEnumerable<Sales.Model.Part>
@if (Model != null && !string.IsNullOrEmpty(Model.PartNumberManufacturer))
{
    @if (Model.PartNumberManufacturer == "Fr")
    {
        <div>
            <p> This product is developed in france </p>
    }
    @if (@Model.PartNumberManufacturer == "Ger")
    {
        <p> This Product is developed in Germany </p>
    }
}

For some reason when I run my query to search for a partnumber .. it only returns the first found partnumber in the database and it does not query for the others. So after research and research online I found that I need to return a collection and iterate each object in that collection.

How would I iterate my collection abd access each object in the collection??

Thank you

Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
SomuchtoLearn
  • 13
  • 1
  • 4

2 Answers2

2

The proper way, where you don't have to write the loop yourself, would be to create a DisplayTemplate for your model:

@model PartNumber
@Html.DisplayFor(m => m.id)

Then you can use that DisplayTemplate in your PartNumberView:

@model IEnumerable<PartNumber>
@Html.DisplayForModel()

This will iterate automatically. Of course this may or may not be feasible, depending on what you want your view to look like.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • this is making sense .. can it be applied to me edited verion.. please see edited version? – SomuchtoLearn Aug 10 '15 at 08:59
  • Either put everything from `@if (Model != null ...` in a DisplayTemplate at `~/Views/Shared/DisplayTemplates/Part.cshtml`, or put a `foreach()` in your view. – CodeCaster Aug 10 '15 at 09:00
1

If you want to iterate the collection inside your view you simply can write this code inside your partial view:

@model IEnumerable<yourModel>
@foreach (var item in Model)
{
    <li>@item.title</li>
}

Update: I think you need something like this:

@model IEnumerable<Sales.Model.Part>
@foreach (var item in Model)
{
    if (Model != null && !string.IsNullOrEmpty(item.PartNumberManufacturer))
    {
        if (item.PartNumberManufacturer == "Fr")
        {
             <p> This product is developed in france </p>
        }
        else if (item.PartNumberManufacturer == "Ger")
        {
             <p> This Product is developed in Germany </p>
        }

    }
}
Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110