Description:
Model:
In
this example we explain that how to Upload, Read and display or bind CSV File
data in asp.net MVC.or how to read data from CSV file and bind data in MVC.Here
we upload file then read it and display it on grid in mvc razor.CSV file is
stored the data in comma separated values.
So
here we demonstrate how to upload CSV file in MVC and then Read CSV file data
and bind it in MVC Grid or html table.
public class EmployeeModel
{
///<summary>
/// Gets or sets EmployeeId.
///</summary>
public int EmployeeId { get; set; }
///<summary>
/// Gets or sets EmployeeName.
///</summary>
public string EmployeeName { get; set; }
///<summary>
/// Gets or sets Designation.
///</summary>
public string Designation { get; set; }
}
Controller:
public class EmployeeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View(new List<EmployeeModel>());
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
List<EmployeeModel> Employees = new List<EmployeeModel>();
string filePath = string.Empty;
if (postedFile != null)
{
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);
//Read the contents of CSV file.
string csvData = System.IO.File.ReadAllText(filePath);
//Execute a loop over the rows.
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
Employees.Add(new EmployeeModel
{
EmployeeId = Convert.ToInt32(row.Split(',')[0]),
EmployeeName = row.Split(',')[1],
Designation = row.Split(',')[2]
});
}
}
}
return View(Employees);
}
}
View:
@using Read_CSV_MVC.Models
@model IEnumerable<EmployeeModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta EmployeeName="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" EmployeeName="postedFile"/>
<input type="submit" value="Import"/>
}
@if (Model.Count()
> 0)
{
<hr/>
<table cellpadding="0" cellspacing="0">
<tr>
<th>Id</th>
<th>EmployeeName</th>
<th>Designation</th>
</tr>
@foreach (EmployeeModel employee in Model)
{
<tr>
<td>@employee.EmployeeId</td>
<td>@employee.EmployeeName</td>
<td>@employee.Designation</td>
</tr>
}
</table>
}
</body>
</html>
Post your sms through few clicks on Clout's Send sms feature, Personalised sms via uploading CSV to send SMS on multiple number in single click and Personalised sms via Phone book to send on group in single click.
ReplyDeleteBulk SMS Software
Great Content. It will useful for knowledge seekers. Keep sharing your knowledge through this kind of article.
ReplyDeleteMVC Training in Chennai