Beispiel #1
0
        public async Task <IActionResult> Edit(Guid id, CarModelEditModel model)
        {
            if (id == null)
            {
                return(this.NotFound());
            }

            var carModel = await this._context.CarModels
                           .SingleOrDefaultAsync(m => m.Id == id);

            if (carModel == null)
            {
                return(this.NotFound());
            }
            if (this.ModelState.IsValid)
            {
                carModel.Name        = model.Name;
                carModel.Description = model.Description;

                await this._context.SaveChangesAsync();

                return(this.RedirectToAction("Details", "CarBrands", new { carId = carModel.CarBrandId }));
            }
            this.ViewData["CarBrandId"] = new SelectList(this._context.CarBrands, "Id", "Name", carModel.CarBrandId);
            return(this.View(model));
        }
Beispiel #2
0
        public async Task <IActionResult> Create(Guid?carBrandId, CarModelEditModel model)
        {
            if (carBrandId == null)
            {
                this.NotFound();
            }

            var fileName = Path.GetFileName(ContentDispositionHeaderValue.Parse(model.ModelPath.ContentDisposition).FileName.Value.Trim('"'));
            var fileExt  = Path.GetExtension(fileName);

            if (!CarModelsController.AllowedExtensions.Contains(fileExt))
            {
                this.ModelState.AddModelError(nameof(model.ModelPath), "This file type is prohibited");
            }

            var carBrand = await this._context.CarBrands
                           .SingleOrDefaultAsync(m => m.Id == carBrandId);

            if (carBrand == null)
            {
                this.NotFound();
            }

            if (this.ModelState.IsValid)
            {
                var carModel = new CarModel
                {
                    CarBrandId  = carBrand.Id,
                    Name        = model.Name,
                    Description = model.Description
                };

                var attachmentPath = Path.Combine(this.hostingEnvironment.WebRootPath, "attachments/models", carModel.Id.ToString("N") + fileExt);
                carModel.ModelPath = $"/attachments/models/{carModel.Id:N}{fileExt}";
                using (var fileStream = new FileStream(attachmentPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read))
                {
                    await model.ModelPath.CopyToAsync(fileStream);
                }


                carModel.Id = Guid.NewGuid();
                this._context.Add(carModel);
                await this._context.SaveChangesAsync();

                return(this.RedirectToAction("Details", "CarBrands", new { carId = carBrand.Id }));
            }
            this.ViewData["CarBrandId"] = new SelectList(this._context.CarBrands, "Id", "Name");
            this.ViewBag.CarBrands      = carBrand;
            return(this.View(model));
        }