Hi,
Here I have created sample that will help you out.
Index.aspx(View)
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<input id="fileupload1" type="file" name="file1" />
<input type="submit" value="Import" />
<br />
<br />
<%} %>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<% foreach (System.Data.DataColumn column in ((System.Data.DataTable)Model).Columns)
{%>
<th>
<%= column.ColumnName%>
</th>
<% } %>
</tr>
<%for (int i = 0; i < ((System.Data.DataTable)Model).Rows.Count; i++)
{%>
<tr>
<%
for (int j = 0; j < ((System.Data.DataTable)Model).Columns.Count; j++)
{
%>
<td>
<%= ((System.Data.DataTable)Model).Rows[i][j].ToString()%>
</td>
<% }%>
</tr>
<% } %>
</table>
HomeController(Contoller)
[HttpGet]
public ActionResult Index()
{
DataTable dt = new DataTable();
return View(dt);
}
[HttpPost]
[ActionName("Index")]
public ActionResult Import()
{
DataTable dt = new DataTable();
HttpFileCollectionBase hfc = HttpContext.Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFileBase hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = Path.GetFileName(hpf.FileName);
string csvPath = Server.MapPath("~/Files/") + fileName;
hpf.SaveAs(csvPath);
dt = ReadToEnd(csvPath);
if (System.IO.File.Exists(csvPath))
{
System.IO.File.Delete(csvPath);
}
}
}
return View("Index", dt);
}
private DataTable ReadToEnd(string filePath)
{
DataTable dtDataSource = new DataTable();
string[] fileContent = System.IO.File.ReadAllLines(filePath);
if (fileContent.Count() > 0)
{
string[] columns = fileContent[0].Split(',');
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add(columns[i]);
}
for (int i = 1; i < fileContent.Count(); i++)
{
string[] rowData = fileContent[i].Split(',');
dtDataSource.Rows.Add(rowData);
}
}
return dtDataSource;
}
Sample.csv
Id,Name,Country
1,John Hammond,United States
2,Mudassar Khan,India
3,Suzanne Mathews,France
4,Robert Schidner,Russia
Screenshot