Wednesday, 25 May 2016

Read the Data from text Document line by Line display in MVC controls

step 1:

file1.txt
InvoiceNo~123456
InvoiceDate~10/06/2016
Total~10000
Count~13478
CompanyName~WallMart
Address~Chennai
PhoneNo~044-12345678



Test.cshtml (View)
@model IEnumerable<Sample.Models.Test>
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "View Data";
}
<div class="container">
    @if (Model.Count() != 0)
    {
        foreach (var item in Model)
        {  <div class="row">
            <div class="col-md-12">
                <div class="col-md-4">
                    @Html.LabelFor(x => item.Name, item.Name, new { @Class="lbl" })
                </div>
                <div class="col-md-8">
                    @Html.EditorFor(x => item.Value, item.Value.GetType().Name)
                </div>
            </div>
        </div>                      
        }
    }
</div>

Test.cs (Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Sample.Models
{
    public class Test
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }
}

TestController.cs (Controller)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Sample.Models;

namespace Sample.Controllers
{
    public class TestController : Controller
    {        
        // GET: /Test/
        public ActionResult Index()
        {
            string filepath = Server.MapPath("~/file/file1.txt");
            string content = string.Empty;
            try
            {           
                int counter = 0;
                List<Test> urllist = new List<Test>();                
                System.IO.StreamReader file = new System.IO.StreamReader(filepath);                
                while ((content = file.ReadLine()) != null)
                {
                    string[] values = content.Split('~');
                    urllist.Add(new Test()
                    {
                       Name = values[0].ToString(),
                       Value = values[1].ToString()
                    });                                                                             
                    counter++;                                  
                }
                file.Close();
                return View(urllist);                
            }
            catch (Exception exc)
            {
                return Content("Error !");
            }            
        }
    }
}

No comments: