所以我在我的控制器中有动作方法,它从我通过网络上传的CSV文件中获取数据
我想将该数据传递给Insert控制器,以便CSV中的数据自动插入到我的数据库中的表中并将其传递给视图
我使用的是CSV HELPER,MVC
public ActionResult ImportCSV(HttpPostedFileBase file, int compID)
{
var compName = db.CourierCompanies.Find(compID);
string path = null;
List<MyViewModel> csvD = new List<MyViewModel>();
try
{
if(file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = AppDomain.CurrentDomain.BaseDirectory + "upload\\" + fileName;
file.SaveAs(path);
var csv = new CsvReader(new StreamReader(path));
var invoCSV = csv.GetRecords<ImportCsV>();
foreach(var i in invoCSV)
{
MyViewModel iCSV = new MyViewModel();
iCSV.CustID = i.cust_id;
iCSV.Fullname = i.fullname;
iCSV.CustComp = i.company;
iCSV.InvoiceNo = i.rec_no;
iCSV.InsertDate = DateTime.Parse(i.doc_dt);
iCSV.Road = i.w_addr1;
iCSV.City = i.w_city;
iCSV.Zip = i.w_zip;
iCSV.Phone = i.w_phone;
iCSV.Status = "BelumTerkirim";
iCSV.compID = compID;
iCSV.CompName = compName.CompName;
iCSV.StatDate = DateTime.Now;
csvD.Add(iCSV);
}
}
}
catch
{
ViewData["Error"] = "Upload Failed";
}
return View();
}
插入控制器
public ActionResult Create( MyViewModel model, int compID, HttpPostedFileBase file)
{
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
model.Image = ms.GetBuffer();
}
}
var cust = new Customer()
{
CustID = model.CustID,
Phone = model.Phone,
CustComp = model.CustComp,
Fullname = model.Fullname
};
var addrDet = new AddrDetail()
{
Road = model.Road,
City = model.City,
Zipcode = model.Zip
};
var invoice = new Invoice()
{
InvoiceNo = model.InvoiceNo
};
var stat = new Status()
{
Status1 = model.Status,
StatDate = model.StatDate,
Ket = model.Ket
};
var image = new Models.Image()
{
Image1 = model.Image
};
var detail = new DetailPengiriman()
{
NamaPenerima = model.NamaPenerima,
StatusPenerima = model.StatusPenerima,
TrDate = model.TrDate,
InsertDate = model.InsertDate
};
if (ModelState.IsValid )
{
//customer
db.Customers.Add(cust);
detail.CustID = cust.CustID;
invoice.CustID = cust.CustID;
//addrDet
db.AddrDetails.Add(addrDet);
cust.AddrDetID = addrDet.AddrDetID;
//invoice
db.Invoices.Add(invoice);
stat.InvoiceNo = invoice.InvoiceNo;
image.InvoiceNo = invoice.InvoiceNo;
detail.InvoiceNo = invoice.InvoiceNo;
//status
db.Status.Add(stat);
detail.StatusID = stat.StatusID;
////image
db.Images.Add(image);
detail.ImageID = image.ImageID;
//detail
detail.CompID = compID;
db.DetailPengirimen.Add(detail);
db.SaveChanges();
return RedirectToAction("Index", new { compID = detail.CompID});
}
return View();
}
答案 0 :(得分:1)
您可以在另一个类中抽象该业务逻辑,并在CSV操作中实例化它。
通过这种方式,您可以调用方法从两个操作中插入客户!