2015-05-12

ASP.NET MVC4 + Kendo UI - FileUpload Sample

使用 kendoui 同時上傳 model 與 檔案

Javascript:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
[HttpPost]
public ActionResult Upload([Bind(Include = "Title")]MyDataViewModel model)
{
    if (model == null) throw new Exception("Null");
    using (var transaction = _db.Database.BeginTransaction(IsolationLevel.Serializable))
    {
        var tempFileList = new List<MyFile>();
        try
        {
            model.CreateTime = DateTime.Now;
            model.CreateUser = Auth.CurrentId;
            _db.MyDataTable.Add(model);
            _db.SaveChanges();

            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                var fileEntity=new MyFile(file);

                // do save file
                tempFileList.Add(fileEntity);
            }

            transaction.Commit();
            return new JsonResult()
            {
                Data = "Success",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        catch (Exception ex)
        {
            foreach (var file in tempFileList)
            {
                // do remove file
            }
            transaction.Rollback();
            return new JsonResult()
            {
                Data = "Failure",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }
}

沒有留言:

adsense