예제 #1
0
        public ActionResult Create([Bind(Include = "Id,FirstName,LastName,Position,Email,PhoneNumber")] ContactModel contactModel,
            HttpPostedFileBase upload)
        {
            LogManager logManager = new LogManager(db);
            if (ModelState.IsValid)
            {
                // check if image was uploaded
                if(upload != null && upload.ContentLength > 0 ){
                    logManager.LogFileUploadEvent(upload.FileName);
                    var avatar = new File
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileType.Avatar,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    contactModel.Files = new List<File> { avatar };
                }
                db.Contacts.Add(contactModel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(contactModel);
        }
예제 #2
0
        public ActionResult Edit(int? id, HttpPostedFileBase upload)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var contactModel = db.Contacts.Find(id);
            //if (contactModel == null)
            //{
            //    return HttpNotFound();
            //}
            if (TryUpdateModel(contactModel, "", new string[] { "FirstName", "LastName", "Position", "Email", "PhoneNumber" }))
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    // check if user have Avatar uploaded
                    if (contactModel.Files.Any(f => f.FileType == FileType.Avatar))
                    {
                        db.files.Remove(contactModel.Files.First(f => f.FileType == FileType.Avatar));
                    }
                    var avatar = new File
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileType.Avatar,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    contactModel.Files = new List<File> { avatar };
                }
                db.Entry(contactModel).State = EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            return View(contactModel);
        }