Pages

Tuesday, March 1, 2016

MVC: Splitting a list without splitting the dataset

Today I needed to split a list of companies into Companies and Relocation Companies.  The data is in the same table and model, but presentation rules for this project require 2 lists.

SO:

Taking a single dataset from the controller:

        // GET: Companies
        public ActionResult Index()
        {
            return View(db.Companies.ToList());
        }

I took this bit of view/index code from the auto-generated “Code First From Database” tool…

<h3>Companies</h3>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CompanyName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.isActive)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.isReloCompany)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ChangedBy)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastChangedDate)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.CompanyName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.isActive)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.isReloCompany)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ChangedBy)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastChangedDate)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.UniqueId }) |
                @Html.ActionLink("Details", "Details", new { id = item.UniqueId })
            </td>
        </tr>
    }

</table>

And I made 2 copies (in my case I will only ever need 2 lists).  I changed the highlighted line in the above to…

    @foreach (var item in Model.Where(d => d.isReloCompany == false).OrderBy(d=>d.CompanyName))

Note that I can add LINQ into the view easily and I did not have to split my list beforehand in the controller.  The second copy of this line has .isReloCompany==true.






Share This!

Contact Us

Name

Email *

Message *