Exemple #1
0
        public ActionResult Add(Contact contact, HttpPostedFileBase file)
        {
            #region step#1 : Fetch Countries and States

            var allCountries = new List <Country>();
            var allStates    = new List <State>();
            using (var dbContext = new ContactDbContext())
            {
                allCountries = dbContext.Countries.OrderBy(c => c.CountryName).ToList();
                if (contact.ContactId > 0)
                {
                    // Fetching all the states whose countryId == contact.CountryId (i.e all the states of respective selected country)
                    allStates = dbContext.States.Where(s => s.CountryId.Equals(contact.CountryId)).OrderBy(s => s.StateName).ToList();
                }
            }
            ViewData["Countries"] = new SelectList(allCountries, "CountryId", "CountryName", contact.CountryId);
            ViewData["States"]    = new SelectList(allStates, "StateId", "StateName", contact.StateId);
            #endregion

            #region step#2 : Validate the file if selected

            if (file != null)
            {
                if (file.ContentLength > (512 * 1000))  // if file size > then 512KB
                {
                    ModelState.AddModelError("FileErrorMessage", "File size must be within 512KB");
                }

                bool isFileTypeValid = false;

                isFileTypeValid = ContactDbRepository.ValidateFileType(file);

                if (isFileTypeValid == false)
                {
                    ModelState.AddModelError("FileErrorMessage", "only .png , .gif, .jpeg , .jpg file types are allowed");
                }
            }
            #endregion

            #region step#3 : Validate Model and Save the data into the database

            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    string targetPath = Server.MapPath("~/Content/Images");
                    ContactDbRepository.SaveImageFile(contact, file, targetPath);
                }

                ContactDbRepository.AddContact(contact); // adding and saving contact data into database

                return(RedirectToAction("AllContacts", "Home"));
            }
            #endregion

            return(View(contact));
        }