asp.net mvc

Hi Guys,

I would like to get some suggestion from you to how I can loop in my application:

Here is my situation:

I'm trying to return each refer with multiple items, but unfortunately I'm getting  each referense number for each item:

Here is how my app look like:

myapp


Here is my controller:

const int pageSize = 10;

        [HttpGet]
        public ActionResult Index(int page = 1, int sortBy = 6, bool isAsc = false, string Name = null, string Name1 = null)
        {
            ALThompsonCRMEntities _db = new ALThompsonCRMEntities();


            var apps = (from i in _db.t_InventoryCount join e in _db.t_InventoryCountEntry
                        on i.ID equals e.InventoryCountID select new Countitems
            {
                Reference = i.Reference,
                Status = i.Status,
                DateCreated = i.DateCreated,
                DateCompleted = i.DateCompleted,
                CountedBy = i.CountedBy,

                ItemID = e.ItemID,
                Itemlookupcode = e.Itemlookupcode,
                ItemDescription = e.ItemDescription,
                CurrentInventory = e.CurrentInventory,
                CountQty = e.CountQty
                
            });
                        
            if (Name != null && Name != "")
                apps = apps.Where(p => p.Reference.Contains(Name));
            if (Name1 != null && Name1 != "") 
                apps = apps.Where(p => p.CountedBy.Contains(Name1));



            #region Sorting
            switch (sortBy)
            {
                case 1:
                    apps = isAsc ? apps.OrderBy(p => p.Reference) : apps.OrderByDescending(p => p.Reference);
                    break;
                case 2:
                    apps = isAsc ? apps.OrderBy(p => p.Status) : apps.OrderByDescending(p => p.Status);
                    break;
                case 3:
                    apps = isAsc ? apps.OrderBy(p => p.DateCreated) : apps.OrderByDescending(p => p.DateCreated);
                    break;
                case 4:
                    apps = isAsc ? apps.OrderBy(p => p.DateCompleted) : apps.OrderByDescending(p => p.DateCompleted);
                    break;
                case 5:
                    apps = isAsc ? apps.OrderBy(p => p.CountedBy) : apps.OrderByDescending(p => p.CountedBy);
                    break;
                default:
                    apps = apps.OrderByDescending(p => p.Reference);
                    break;
            }
            #endregion
            List<Countitems> lstPo = apps.ToList();
            double cnt = (double)lstPo.Count();
            lstPo = lstPo
               .Skip((page - 1) * pageSize)
               .Take(pageSize)
               .ToList();
            ViewBag.TotalPages = (int)Math.Ceiling(cnt / pageSize);
            ViewBag.TotalRows = cnt;
            ViewBag.CurrentPage = page;
            ViewBag.PageSize = pageSize;
            ViewBag.SortBy = sortBy;
            ViewBag.IsAsc = isAsc;
            ViewBag.Name = Name;
            ViewBag.Name1 = Name1;
            return View(lstPo);
        }

Open in new window


Here is my view:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@model IEnumerable<ALThompsonCRM.Models.ViewModel.Countitems>


@helper buildLinks(int start, int end, string innerContent)
{
    for (int i = start; i <= end; i++)
    {
        <a class="@(i == ViewBag.CurrentPage ? "Current" : "")" href="@Url.Action("Index", "Inventory", new { page = i, sortBy = ViewBag.sortBy, isAsc = ViewBag.isAsc, Name = ViewBag.Name, Name1 = ViewBag.Name1, fromdate = ViewBag.fromdate, todate = ViewBag.todate })">@(innerContent ?? i.ToString())</a>
    }
}

@helper pageLinks()
{
    const int maxPages = 11;

    if (ViewBag.TotalPages <= maxPages)
    {
        @buildLinks(1, (int)ViewBag.TotalPages, null)
        return;
    }

    int pagesAfter = ViewBag.TotalPages - ViewBag.CurrentPage; // Number of pages after current
    int pagesBefore = ViewBag.CurrentPage - 1; // Number of pages before current

    if (pagesAfter <= 4)
    {
        @buildLinks(1, 1, null) // Show 1st page

        int pageSubset = ViewBag.TotalPages - maxPages - 1 > 1 ? ViewBag.TotalPages - maxPages - 1 : 2;
        @buildLinks(pageSubset, pageSubset, "...") // Show page subset (...)

                                                @buildLinks(ViewBag.TotalPages - maxPages + 3, ViewBag.TotalPages, null) // Show last pages

        return; // Exit
    }

    if (pagesBefore <= 4)
    {
        @buildLinks(1, maxPages - 2, null) // Show 1st pages


        int pageSubset = maxPages + 2 < ViewBag.TotalPages ? maxPages + 2 : ViewBag.TotalPages - 1;
        @buildLinks(pageSubset, pageSubset, "...") // Show page subset (...)

                                                @buildLinks(ViewBag.TotalPages, ViewBag.TotalPages, null) // Show last page

        return; // Exit

    }

    if (pagesAfter > 4)
    {
        @buildLinks(1, 1, null) // Show 1st pages

        int pageSubset1 = ViewBag.CurrentPage - 7 > 1 ? ViewBag.CurrentPage - 7 : 2;
        int pageSubset2 = ViewBag.CurrentPage + 7 < ViewBag.TotalPages ? ViewBag.CurrentPage + 7 : ViewBag.TotalPages - 1;

        @buildLinks(pageSubset1, pageSubset1, pageSubset1 == ViewBag.CurrentPage - 4 ? null : "...") // Show 1st page subset (...)

                                                                                                    @buildLinks(ViewBag.CurrentPage - 3, ViewBag.CurrentPage + 3, null) // Show middle pages

        // Show 2nd page subset (...)
        // only show ... if page is contigous to the previous one.
        @buildLinks(pageSubset2, pageSubset2, pageSubset2 == ViewBag.CurrentPage + 4 ? null : "...")
        @buildLinks(ViewBag.TotalPages, ViewBag.TotalPages, null) // Show last page

        return; // Exit

    }

}

@helper sortLink(string name, int id)
{
    <a href="@Url.Action("Index", "Inventory", new { sortby = id, isasc = (id == ViewBag.sortBy ? (!@ViewBag.isAsc).ToString().ToLower() : true), Name = ViewBag.Name, Name1 = ViewBag.Name1, po_type = ViewBag.potype, fromdate = ViewBag.fromdate, todate = ViewBag.todate })">@name</a>
    if (id == ViewBag.sortBy)
    {
        <span class="arrow @(ViewBag.isAsc ? "up" : "down" )"></span>
    }
}




<div class="panel panel-primary">
    <div class="panel-heading">
        Inventory
        <div class="btn-group pull-right">
           
        </div>
        

    </div>
    <div class="panel-body">
        <form action="@Url.Action("Index", "Inventory")" method="get">
            <table class="table table-responsive">
                <tr class="highlighted">
                    <td>
                        <div>
                            Reference:
                            <input id="Name" name="Name" class="form-control" type="text" value="@ViewBag.Name" />
                        </div>
                    </td>

                    <td>
                        <div>
                            Count By:
                            <input id="Name1" name="Name1" class="form-control" type="text" value="@ViewBag.Name1" />
                        </div>
                    </td>

                    <td>
                        <input type="submit" value="Search" class="btn btn-sm btn-primary" />
                    </td>
                </tr>
            </table>

        </form>
       
     
        <div id="table-content" class="table-responsive">
            <table id="item_main" class="table table-responsive table-bordered">
                <tr class="info">
                    <th>@sortLink("Reference", 1)</th>
                    <th>@sortLink("Status", 2)</th>
                    <th>@sortLink("Date Created", 3)</th>
                    <th>@sortLink("Date Completed", 4)</th>
                    <th>@sortLink("Count By", 5)</th>
                    @*<th>Options</th>*@
                </tr>

                @{
                    int i = 1;
                    string chkid = "chkid" + i.ToString();
                    string appid = "appid" + i.ToString();
                    }



                @foreach (var item in Model)
                {
                    
                    string coun_qty = "CountQty" + i;
                    
                    <tr style="cursor:pointer" class="header">
                        <td id="inid"><span>+</span> @item.Reference</td>
                        <td>@item.Status</td>
                        <td>@item.DateCreated</td>
                        <td>@item.DateCompleted</td>
                        <td>@item.CountedBy</td>
                    </tr>
    <tr style="display: none;" class="info">
        <td colspan="4">
            <table class="table table-condensed">
                <tr>
                    <td>
                        Itemlookupcode
                    </td>
                    <td>@item.Itemlookupcode</td>
                    <td>
                        Description
                    </td>
                    <td>
                        @item.ItemDescription
                    </td>
                    <td>
          
                </tr>
                <tr>
                    <td>
                        ItemID
                    </td>
                    <td>
                        @item.ItemID
                    </td>
                  
                </tr>
                <tr>
                    <td>
                        Current Inventory
                    </td>
                    <td>
                        @item.CurrentInventory
                    </td>
                    
                </tr>
                <tr>
                    <td>
                        Count Qty
                    </td>
                    <td>
                        @Html.TextBox(coun_qty, item.CountQty)
                    </td>
                 

                    <td></td>
                    <td></td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" value="Update" class="btn btn-sm btn-primary" />&nbsp;&nbsp;<input type="submit" value="Print " class="btn btn-sm btn-primary" />
                        <a title="Picture" class="icon-picture icon-2x pull-right" onclick="Showpic(@item.ItemID)"></a>
                    </td>
                                            
                    
                 
                </tr>

            </table>
            @*<input type="hidden" name="@id_ctrlname" id="@id_ctrlname" value="@item.ID" />*@
        </td>
    </tr>

                        i++;
                        chkid = "chkid" + i.ToString();
                        appid = "appid" + i.ToString();

                }

            </table>





            @if (i > 1)
            {
                <div class="pagination-lg center-block">
                    <span style="float:right">Total : <a href="#">@ViewBag.TotalRows</a></span>
                    Pages : @pageLinks()
                </div>
            }
            else
            {
                <div class="label">
                    Records Not Found
                </div>
            }
        </div>

    </div>
</div>






@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">
    jQuery(function ($) {
        $("#WaitDialog").dialog({
            autoOpen: false
        });
        $(document).ajaxStart(function () {
            $("#WaitDialog").dialog('open');
        }).ajaxStop(function () {
            $("#WaitDialog").dialog('close');
        }).ajaxSuccess(function () {
        });

        $(".datepicker").datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true
        });


    });

    $(document).ready(function () {
        $('#item_main tr.header').click(function () {
            $(this).find("span").text(function (_, value) { return value == "+" ? "-" : "+" });
            $(this).nextUntil("tr.header").slideToggle(10, function () {
            });
        });
    });


    function Showitems(id) {
        var url = "@System.Configuration.ConfigurationManager.AppSettings["webUrl"]";
            url = url + "Inventory/Itemsrefer/" + id;
            window.open(url, '_blank', "width=1200, height=800", 'resizable=No');
        }

        function Showpic(id) {
            var url = "@System.Configuration.ConfigurationManager.AppSettings["webUrl"]";
            url = url + "Inventory/Picture/" + id;
            window.open(url, '_blank',"width=500, height=500", 'resizable=No');
        }




    </script>
}

Open in new window


What I'm trying to do is to loop each item to each reference
LVL 1
Moti Mashiah.NET DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David Johnson, CD, MVPOwnerCommented:
instead of the reference you probably want the item lookup code
  Reference = i.Reference,

why is the reference always the same? or is there only 1 with reference and the remainder are null?
0
Moti Mashiah.NET DeveloperAuthor Commented:
Hi David,

Thank you for your answer. I think that i didn't explain the situation well as I'm very new in this world.

I would like to show you the 2 tables I work with, one of them is the header and the other is the child.

The table has relationship by FK and what I would like to do is to query all the items belong to one reference. each reference contains couple of items.

Please, review my tables schema and I hope it will help to understand my needs:
Note:
The t_inventorycount is my header table, for now i'm getting reference to each item and I would like to have one reference for multiple items when i open to + sign.

CREATE TABLE [dbo].[t_InventoryCount](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Reference] [nvarchar](30) NOT NULL,
	[Status] [int] NOT NULL,
	[DateCreated] [datetime] NOT NULL,
	[DateCompleted] [datetime] NULL,
	[CountedBy] [nvarchar](30) NOT NULL,
 CONSTRAINT [PK_t_InventoryCount] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[t_InventoryCountEntry]    Script Date: 5/4/2015 7:03:40 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[t_InventoryCountEntry](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ItemID] [int] NOT NULL,
	[Itemlookupcode] [nvarchar](50) NOT NULL,
	[ItemDescription] [nvarchar](60) NULL,
	[InventoryCountID] [int] NOT NULL,
	[CurrentInventory] [float] NOT NULL,
	[CountQty] [float] NOT NULL,
	[ItemPicture] [int] NULL,
 CONSTRAINT [PK_t_InventoryCountEntry] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[t_InventoryCountEntry]  WITH CHECK ADD  CONSTRAINT [FK_t_InventoryCountEntry_t_InventoryCount] FOREIGN KEY([InventoryCountID])
REFERENCES [dbo].[t_InventoryCount] ([ID])
GO
ALTER TABLE [dbo].[t_InventoryCountEntry] CHECK CONSTRAINT [FK_t_InventoryCountEntry_t_InventoryCount]
GO

Open in new window

0
Moti Mashiah.NET DeveloperAuthor Commented:
One more thing the reference the same and goes like per item for example if reference has 10 items so the reference will show 10 times and each time with different items. what I wanna do is to eachloop them and get multiple item for one reference.


Thanks,
0
Moti Mashiah.NET DeveloperAuthor Commented:
Found the solution:

just looped twice in my view.

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@model IEnumerable<ALThompsonCRM.Models.ViewModel.Countitems>


@helper buildLinks(int start, int end, string innerContent)
{
    for (int i = start; i <= end; i++)
    {
        <a class="@(i == ViewBag.CurrentPage ? "Current" : "")" href="@Url.Action("Index", "Inventory", new { page = i, sortBy = ViewBag.sortBy, isAsc = ViewBag.isAsc, Name = ViewBag.Name, Name1 = ViewBag.Name1, fromdate = ViewBag.fromdate, todate = ViewBag.todate })">@(innerContent ?? i.ToString())</a>
    }
}

@helper pageLinks()
{
    const int maxPages = 11;

    if (ViewBag.TotalPages <= maxPages)
    {
        @buildLinks(1, (int)ViewBag.TotalPages, null)
        return;
    }

    int pagesAfter = ViewBag.TotalPages - ViewBag.CurrentPage; // Number of pages after current
    int pagesBefore = ViewBag.CurrentPage - 1; // Number of pages before current

    if (pagesAfter <= 4)
    {
        @buildLinks(1, 1, null) // Show 1st page

        int pageSubset = ViewBag.TotalPages - maxPages - 1 > 1 ? ViewBag.TotalPages - maxPages - 1 : 2;
        @buildLinks(pageSubset, pageSubset, "...") // Show page subset (...)

                                                @buildLinks(ViewBag.TotalPages - maxPages + 3, ViewBag.TotalPages, null) // Show last pages

        return; // Exit
    }

    if (pagesBefore <= 4)
    {
        @buildLinks(1, maxPages - 2, null) // Show 1st pages


        int pageSubset = maxPages + 2 < ViewBag.TotalPages ? maxPages + 2 : ViewBag.TotalPages - 1;
        @buildLinks(pageSubset, pageSubset, "...") // Show page subset (...)

                                                @buildLinks(ViewBag.TotalPages, ViewBag.TotalPages, null) // Show last page

        return; // Exit

    }

    if (pagesAfter > 4)
    {
        @buildLinks(1, 1, null) // Show 1st pages

        int pageSubset1 = ViewBag.CurrentPage - 7 > 1 ? ViewBag.CurrentPage - 7 : 2;
        int pageSubset2 = ViewBag.CurrentPage + 7 < ViewBag.TotalPages ? ViewBag.CurrentPage + 7 : ViewBag.TotalPages - 1;

        @buildLinks(pageSubset1, pageSubset1, pageSubset1 == ViewBag.CurrentPage - 4 ? null : "...") // Show 1st page subset (...)

                                                                                                    @buildLinks(ViewBag.CurrentPage - 3, ViewBag.CurrentPage + 3, null) // Show middle pages

        // Show 2nd page subset (...)
        // only show ... if page is contigous to the previous one.
        @buildLinks(pageSubset2, pageSubset2, pageSubset2 == ViewBag.CurrentPage + 4 ? null : "...")
        @buildLinks(ViewBag.TotalPages, ViewBag.TotalPages, null) // Show last page

        return; // Exit

    }

}

@helper sortLink(string name, int id)
{
    <a href="@Url.Action("Index", "Inventory", new { sortby = id, isasc = (id == ViewBag.sortBy ? (!@ViewBag.isAsc).ToString().ToLower() : true), Name = ViewBag.Name, Name1 = ViewBag.Name1, po_type = ViewBag.potype, fromdate = ViewBag.fromdate, todate = ViewBag.todate })">@name</a>
    if (id == ViewBag.sortBy)
    {
        <span class="arrow @(ViewBag.isAsc ? "up" : "down" )"></span>
    }
}




<div class="panel panel-primary">
    <div class="panel-heading">
        Inventory
        <div class="btn-group pull-right">

        </div>


    </div>
    <div class="panel-body">
        <form action="@Url.Action("Index", "Inventory")" method="get">
            <table class="table table-responsive">
                <tr class="highlighted">
                    <td>
                        <div>
                            Reference:
                            <input id="Name" name="Name" class="form-control" type="text" value="@ViewBag.Name" />
                        </div>
                    </td>

                    <td>
                        <div>
                            Count By:
                            <input id="Name1" name="Name1" class="form-control" type="text" value="@ViewBag.Name1" />
                        </div>
                    </td>

                    <td>
                        <input type="submit" value="Search" class="btn btn-sm btn-primary" />
                    </td>
                </tr>
            </table>

        </form>


        <div id="table-content" class="table-responsive">
            <table id="item_main" class="table table-responsive table-bordered">
                <tr class="info">
                    <th>@sortLink("Reference", 1)</th>
                    <th>@sortLink("Status", 2)</th>
                    <th>@sortLink("Date Created", 3)</th>
                    <th>@sortLink("Date Completed", 4)</th>
                    <th>@sortLink("Count By", 5)</th>
                    @*<th>Options</th>*@
                </tr>

                @{
                    int i = 1;
                    string chkid = "chkid" + i.ToString();
                    string appid = "appid" + i.ToString();
                }



                @foreach (var item in Model)
                {

                    string coun_qty = "CountQty" + i;

                    <tr style="cursor:pointer" class="header">
                        <td id="inid"><span>+</span> @item.Reference</td>
                        <td>@item.Status</td>
                        <td>@item.DateCreated</td>
                        <td>@item.DateCompleted</td>
                        <td>@item.CountedBy</td>
                    </tr>
                    <tr style="display: none;" class="info">
                        <td colspan="4">
                            <table class="table table-bordered">
                                <tr style="background-color: silver;">
                                    <th>lookupcode</th>
                                    <th>ItemID</th>
                                    <th>Item Description</th>
                                    <th>Current Inventory</th>
                                    <th>Count Qty</th>
                                    <th>Options</th>


                                </tr>

                                @foreach (var entry in item.lstEntry)
                                {

                                    <tr>
                                        <td>@entry.Itemlookupcode</td>
                                        <td>@entry.ItemID  </td>
                                        <td>@entry.ItemDescription  </td>
                                        <td style="text-align: center">@entry.CurrentInventory </td>
                                        <td>@Html.TextBox(coun_qty,entry.CountQty) </td>

                                        <td>
                                            <a title="Picture" class="icon-picture icon-2x" onclick="Showpic(@entry.ItemID)"></a>
                                            <a class="icon-remove icon-2x" onclick="return confirm('You want to delete this Item??');" title="Delete" href="/Inventory/Delete/ @entry.ID"></a>
                                        </td>


                                    </tr>

                                }
                            </table>

                            @*<input type="hidden" name="@id_ctrlname" id="@id_ctrlname" value="@item.ID" />*@
                        </td>
                    </tr>

                                i++;
                                chkid = "chkid" + i.ToString();
                                appid = "appid" + i.ToString();

                }

            </table>





            @if (i > 1)
            {
                <div class="pagination-lg center-block">
                    <span style="float:right">Total : <a href="#">@ViewBag.TotalRows</a></span>
                    Pages : @pageLinks()
                </div>
            }
            else
            {
                <div class="label">
                    Records Not Found
                </div>
            }
        </div>

    </div>
</div>



@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">
        jQuery(function ($) {
            $("#WaitDialog").dialog({
                autoOpen: false
            });
            $(document).ajaxStart(function () {
                $("#WaitDialog").dialog('open');
            }).ajaxStop(function () {
                $("#WaitDialog").dialog('close');
            }).ajaxSuccess(function () {
            });

            $(".datepicker").datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true
            });

            $("#dialog").dialog({
                draggable: false,
                autoOpen: false,
                resizable: false,
                modal: true
            });

        });

        $(document).ready(function () {
            $('#item_main tr.header').click(function () {
                $(this).find("span").text(function (_, value) { return value == "+" ? "-" : "+" });
                $(this).nextUntil("tr.header").slideToggle(10, function () {
                });
            });
        });


        function Showitems(id) {
            var url = "@System.Configuration.ConfigurationManager.AppSettings["webUrl"]";
            url = url + "Inventory/Itemsrefer/" + id;
            window.open(url, '_blank', "width=1200, height=800", 'resizable=No');
        }

        function Showpic(id) {
            var url = "@System.Configuration.ConfigurationManager.AppSettings["webUrl"]";
            url = url + "Inventory/Picture/" + id;
            window.open(url, '_blank', "width=500, height=500", 'resizable=No');
        }

        //function Showpic(id) {
        //    $.ajax({
        //            type: "POST",
        //            url: "Inventory/Picture/",
        //            dataType: "html",
        //            data: { pic: id },
        //            success: function (data) {
        //                $("#dialog").html(data);
        //            }
        //        });
        //        $("#dialog").dialog("open");
        //    }




    </script>
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Moti Mashiah.NET DeveloperAuthor Commented:
solved
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.