i have view that i display data and i have button to import .
how i do that ?
What I have tried:
i tried do this in controller
DBEntities db = new DBEntities();
public ActionResult Index()
{
List < Notification > notifications = db.Notifications.ToList();
return View(notifications);
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase excelfile)
{
if(excelfile == null || excelfile.ContentLength == 0)
{
ViewBag.Error = "Please select a excel file";
return View("Index");
}
else
{
if(excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/Content/"+ excelfile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelfile.SaveAs(path);
//Read data from excel sheet
Excel.Application application = new Excel.Application();
Excel.Workbook workBook = application.Workbooks.Open(path);
Excel.Worksheet worksheet = workBook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
List<notification> listnotification = new List<notification>();
for(int row = 3;row < range.Rows.Count; row++)
{
Notification n = new Notification();
n.notification = ((Excel.Range)range.Cells[row, 1]).Text;
n.req_start = DateTime.ParseExact(((Excel.Range)range.Cells[row, 2]).Text, "dd/MM/yyyy", null);
n.type_code = int.Parse(((Excel.Range)range.Cells[row, 2]).Text);
n.req_time = Convert.ToBoolean(((Excel.Range)range.Cells[row, 4]).Text);
n.order_Num = ((Excel.Range)range.Cells[row, 2]).Text;
n.funLoc_Code = int.Parse(((Excel.Range)range.Cells[row, 4]).Text);
n.Customer.customer_name = ((Excel.Range)range.Cells[row, 3]).Text;
listnotification.Add(n);
}
ViewBag.ListNotification = listnotification;
return View("Index");
}
else
{
ViewBag.Error = "Please select a excel file";
return View("Index");
}
}
}
and i create view :-
@model IEnumerable<testproject.models.notification>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
Index
@using (Html.BeginForm("Index", "Notifications", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.Raw(ViewBag.Error)
<input type="file" name="excelfile" />
<input type="submit" value="Import" />
@foreach (var item in Model)
{
}
@Html.DisplayNameFor(model => model.req_start)
| @Html.DisplayNameFor(model => model.type_code)
| @Html.DisplayNameFor(model => model.req_time)
| @Html.DisplayNameFor(model => model.order_Num)
| @Html.DisplayNameFor(model => model.funLoc_Code)
| @Html.DisplayNameFor(model => model.Customer.customer_name)
| |
@Html.DisplayFor(modelItem => item.req_start)
| @Html.DisplayFor(modelItem => item.type_code)
| @Html.DisplayFor(modelItem => item.req_time)
| @Html.DisplayFor(modelItem => item.order_Num)
| @Html.DisplayFor(modelItem => item.funLoc_Code)
| @Html.DisplayFor(modelItem => item.Customer.customer_name)
| @Html.ActionLink("Edit", "Edit", new { id = item.notification }) |
@Html.ActionLink("Details", "Details", new { id = item.notification }) |
@Html.ActionLink("Delete", "Delete", new { id = item.notification })
|
}