Monday, March 12, 2018

ASP.NET MVC : Display data in 2 or more columns


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

Description:
I want to display data in 3 columns. To display data 2 or more columns we have 2 approaches. One use the Bootstarp, if use the bootstrap it adjust itself. 2nd one using the loop, run the loop and differentiate them like odd and even. For 2nd one check this article.

Implementation:
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 MVC application. Create action to retrieve the data from database.

Complete source 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.
Complete source of Index.cshtml:


@model IEnumerable<infinitescroll.Models.CountryMaster>
@{
    ViewBag.Title = "Display data in 2 or more columns in MVC application";
}

<link href="~/css/bootstrap.css" rel="stylesheet" />
<link href="~/css/bootstrap-grid.css" rel="stylesheet" />
<div class="col-md-12">
        <div class="row">
            @foreach (var x in Model)
            {
                <div style="width: 30%; border: 1px solid #000000; margin: 5px 2px; border: 1px solid; padding: 0 0 0 5px; ">
                   Country name : @Html.DisplayFor(modelItem => x.Name)<br />
                    Country Code : @Html.DisplayFor(modelItem => x.CountryCode)
                </div>
            }
        </div>
    </div>







No comments:

Post a Comment