Friday, March 2, 2018

How to show data in 2 columns in MVC application


In this article I am going to explain how to show data in 2 columns in MVC application.

Description:
I am displaying list of all countries in MVC application one record per row but I want to display data in 2 columns. 2 records pre row.

Implementations:

Model

  public partial class CountryMaster
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string CountryCode { get; set; }
    }

Add controller
Add an empty controller to project. Create action to get data from countrymaster table.

Complete code of controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using infinitescroll.Models;
namespace infinitescroll.Controllers
{
    public class CountryMasterController : Controller
    {
        //
        // GET: / CountryMaster /
        testEntities db = new testEntities();
        public ActionResult Index()
        {
            return View(db.CountryMasters.ToList());
        }      
    }
}




Add View
Add view for index action. I have divide the page layout into 2 parts and run the loop. Odd rows are listed on left side and even rows on right side.

Complete source of View

@model IEnumerable<infinitescroll.Models.CountryMaster>
@{
    ViewBag.Title = "Display data in 2 columns in MVC application";
}
<link href="~/css/bootstrap.css" rel="stylesheet" />
<link href="~/css/bootstrap-grid.css" rel="stylesheet" />

<div class="col-md-12">
    @{int oddrow = 0; int evenrow = 0;}
    <div class="col-md-6" style="float:left">
        @foreach (var x in Model)
        {
            if (oddrow % 2 == 0)
            { <div style="border: 1px solid #000000; margin-bottom: 7px; padding: 2px;">
                <label>Country Name :</label>  @Html.DisplayFor(modelItem => x.Name)<br />

                <label>Country Code :</label>  @Html.DisplayFor(modelItem => x.CountryCode)
            </div>
            }
            oddrow++;
        }
    </div>
    <div class="col-md-6" style="float:right">
        @foreach (var x in Model)
        {
            if (evenrow % 2 != 0)
            {
                <div style="border: 1px solid #000000; margin-bottom: 7px; padding: 2px;">
                    <label>Country Name :</label> @Html.DisplayFor(modelItem => x.Name)<br />
                    <label>Country Code :</label>   @Html.DisplayFor(modelItem => x.CountryCode)
                </div>
            }
            evenrow++;
        }
    </div>
</div>





No comments:

Post a Comment