Azhar Hussain
Azhar Hussain

Reputation: 91

Display Data in Table in Foreach Loop with single repetition as well MVC 5

I want to display a table in following format:
View Image

I'm getting the data by following query:

var rate_list = (from r in db.rate_list
    where r.rate_list_type_id == get_type_id.rate_list_type_id
    group r by r.item.item_category_id
    into gr
    select new RateList()
    {
        category_name = gr.FirstOrDefault().item.item_category.category_name,
        item_name = gr.Select(r => new ItemName()
        {
            item_name = gr.FirstOrDefault().item.item_name

        }).ToList()
    }).ToList();

And then in View I'm doing something like:

@foreach (var item in Model.complete)
    {
        <tr style="border: 1px solid black;">
        <td rowspan="@Model.complete.Count()"></td>
        <td colspan="3">@item.category_name</td>

        @foreach(var t in item.item_name)
        {
            <td>@t.item_name</td>
            <td>@t.item_unit</td>
            <td>@t.item_price</td>
        }
        </tr>               
    } 

I'm not sure how can i output the same result as shown in image.
Any help would be appreciated.

Edit
I am currently getting this

Output

Edit
This is my ViewModel

public class RateList
    {
        public string category_name { get; set; }        
        public IEnumerable<ItemName> item_name { get; set; }
    }

    public class ItemName
    {
        public string item_name { get; set; }
    }

Edit

Right now i have this output

EDIT 2
Latest OUTPUT

EDIT 3
Latest Output

Upvotes: 1

Views: 2049

Answers (1)

Udara Kasun
Udara Kasun

Reputation: 2226

Try this

<table>
        <thead>
            <tr>
                <th>SER</th>
                <th colspan="2">Items</th>
                <th>AU</th>
                <th>1 X Block</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>        
            @{ 
                int i=0;
                foreach (var item in Model.complete) {

                    <tr>
                        <td rowspan="@(item.item_name.Count+1)"></td>
                        <td colspan="2">@item.category_name</td>
                        <td> </td>
                        <td> </td>
                        <td> </td>
                    </tr>
                     int alp=65;
                    foreach (var t in item.item_name) {                           
                        <tr>
                            <td>@((char)(alp++))</td>
                            <td>@t.item_name</td>
                            <td>@t.item_unit</td>
                            <td>@t.item_price</td>
                        </tr>
                    }
                    i++;
                }
            }
        </tbody>
</table>

Upvotes: 1

Related Questions