Domanda

I have a model like as follows:

public class Category
{
    [Key]
    public int Id { get; set; }

    [StringLength(200), Required, DataType(DataType.Text)]
    public string Title { get; set; }

    [Display(Name = "Parent Category")]
    public int? ParentId { get; set; }

    [DisplayFormat(NullDisplayText = "Root")]
    public virtual Category ParentCategory { get; set; }

    public virtual ICollection<Category> ChildCategories { get; set; }
}

Which is hierarchical in nature, 'ParentId' reference to 'Id' as self referencing. With this, I'm trying to display the Data as follows:

+--------+-----------------+
| S. No  |        Name     |
+--------+-----------------+
|   1    |  Parent One     |
+--------+-----------------+
|   1.1  |  Child-1 of One |
+--------+-----------------+
|   1.2  |  Child-2 of One |
+--------+-----------------+
|   2    |  Parent Two     |
+--------+-----------------+
|   2.1  |  Child-1 of Two |
+--------+-----------------+
|   3    |  Parent Three   |
+--------+-----------------+

Please help me on this.

È stato utile?

Soluzione

You can count the Total Child Numbers using an group by parentId and then count

Here is my solution

Define an ViewModel

public class CategoryViewMoel
{
    public IEnumerable<ParentCategoryInfo> parentCategoryInfo { get; set; }
    public int SN { get; set; }
    public int ChildSN { get; set; }
}

public class ParentCategoryInfo
{
    public int? ParentId { get; set; }
    public int TotalChild { get; set; }
}

In The Controller

var model = new CategoryViewMoel();

var parentCategory =  from r in db.Categories
                      where r.ParentCategory != null
                      group r by r.ParentId into newGroup
                      select new ParentCategoryInfo 
                      {
                          TotalChild = newGroup.Count(),
                          ParentId = newGroup.Key,
                      };
model.SN = 1;
model.ChildSN = 1;
model.parentCategoryInfo = parentCategory;

Lastly In your View

<table>
<thead>
    <tr>
        <th>S. No</th>
        <th>Name</th>
    </tr>
</thead>
<tbody>
        @foreach (var parent in Model.parentCategoryInfo)
        {
            <tr>
                <td>@Model.SN </td>
                <td>Parent @Model.SN</td>
            </tr>

            for (var i = Model.ChildSN;  i <= parent.TotalChild; i++)
            {
                <tr>
                    <td>@Model.SN.@i</td>
                    <td>Child - @i of @Model.SN</td>
                </tr>

            Model.ChildSN = 1;
            Model.SN++;
        }
</tbody>

The Mapping form numerical to words can be done by building an customized helper function to achieve this, there are plenty of examples in SO

converting numbers in to words C#

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top