public IActionResult Create(CreateCarViewModel model) { try { if (ModelState.IsValid) { string uniqueFileName = ProcessUploadFile(model); Car newCar = new Car { CarModel = model.CarModel, Prijs = model.Prijs, Content = model.Content, PhotoCar = uniqueFileName, CreatedDate = DateTime.Now, IsAvailableForRent = true, }; _carRepository.Add(newCar); return(RedirectToAction("Details", "Cars", new { id = newCar.CarId })); } return(View()); } catch (Exception ex) { _logger.LogError(ex, $"When trying to create a new car."); throw; } }
public async Task <IActionResult> Add(CreateCarViewModel model, int modelId, int engineId) { if (!this.ModelState.IsValid) { return(this.RedirectToAction("Error", "Home")); } try { var createCarServiceModel = new CreateCarServiceModel() { Id = model.Id, ProductionDate = model.ProductionDate, VIN = model.VIN, Price = model.Price, Color = model.Color, ModelId = modelId, EngineId = engineId }; this.car.Create(createCarServiceModel); await this._carHub.Clients.All.SendAsync("NewOrder"); return(RedirectToAction("All")); } catch (Exception x) { LogExceptionWithMessage(x); ViewBag.Section = "error"; FillViewBagWithDataForSelectInView(); return(View()); } }
public async Task <bool> AddNewCar(CreateCarViewModel newCar) { Car car = new Car(); try { if (newCar != null) { car.Make = newCar.Make; car.Model = newCar.Model; car.VehicleType = VehicleTypes.Car; car.BodyType = newCar.BodyType; car.Badge = newCar.Badge; car.Color = newCar.Badge; car.Condition = newCar.Badge; car.carType = newCar.carType; await _dataRepository.CreateCar(car); return(true); } return(false); } catch (Exception ex) { return(false); } }
public ActionResult Create(CreateCarViewModel viewModel, int customerId) { var currentUser = manager.FindById(User.Identity.GetUserId()); var customer = customersRepo.GetCustomerById(customerId); if (customer == null || customer.User != currentUser) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } if (ModelState.IsValid) { var car = new Car(); car.Manufacturer = viewModel.Manufacturer; car.Model = viewModel.Model; car.VIN = viewModel.VIN; car.EngineCode = viewModel.EngineCode; car.PlateCode = viewModel.PlateCode; car.Year = viewModel.Year; car.FuelType = viewModel.FuelType; car.User = currentUser; car.Customer = customer; carsRepo.InsertCar(car); carsRepo.Save(); return(RedirectToAction("CarsByCustomer", customerId)); } return(View(viewModel)); }
public async Task <IActionResult> Create([Bind("Marca,Descripcion,Modelo,Precio,Kilometros,Estado,Foto")] CreateCarViewModel car) { if (ModelState.IsValid) { string guidImagen = null; if (car.Foto != null) { string ficherosImagenes = Path.Combine(hosting.WebRootPath, "img"); guidImagen = Guid.NewGuid().ToString() + car.Foto.FileName; string rutaDefinitiva = Path.Combine(ficherosImagenes, guidImagen); using (var fileStream = new FileStream(rutaDefinitiva, FileMode.Create)) { car.Foto.CopyTo(fileStream); } } Car newCar = new Car(); newCar.Descripcion = car.Descripcion; newCar.Modelo = car.Modelo; newCar.Precio = car.Precio; newCar.Estado = car.Estado; newCar.Kilometros = car.Kilometros; newCar.MarcaId = car.Marca; newCar.PathImg = guidImagen; _context.Add(newCar); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View()); }
public ActionResult CreateCar(CreateCarViewModel item) { var model = _carModelService.GetCarModels().ToList().FirstOrDefault(it => it.Name == item.ModelName); if (model == null) { ModelState.AddModelError("ModelName", "Выберите модель авто!"); } if (ModelState.IsValid) { var carDto = new CarDTO { CarModelId = model.Id, RentalCenterId = 1 }; _carService.CreateCar(carDto); } var ModelsNames = new List <string>(); foreach (var it in _carModelService.GetCarModels()) { ModelsNames.Add(it.Name); } ViewBag.CarModel = ModelsNames; return(RedirectToAction("CreateCar")); }
// public ViewResult Edit(int id) // private string Processupload(datatype du parameter nom du parameter) private string ProcessUploadFile(CreateCarViewModel model) // return type { string uniqueFileName = null; // creer var comme type string dont la valeur et nul. if (model.Photo != null) // objet model avec property photo/ je check si la valeur de ma property photo qui se trouve dans l'objet model existe. /* * object objectname : * Prop = value * Id = 1 * Name = 'test' * * if(objectname.Name (==)== 'custom') */ { string pathnameofuploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images"); uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName; string filePath = Path.Combine(pathnameofuploadsFolder, uniqueFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { model.Photo.CopyTo(fileStream); } } return(uniqueFileName); }
public IActionResult Create() { var vm = new CreateCarViewModel { Vehicle = new Vehicle(), Brands = ctx.Brands.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }), Bodies = ctx.Bodies.Select(x => new SelectListItem { Text = x.BodyName, Value = x.Id.ToString() }), Dealerships = ctx.Dealerships.Select(x => new SelectListItem { Text = x.City, Value = x.Id.ToString(), }) }; return(View(vm)); }
public Car Edit(int id, CreateCarViewModel car) { Car editedCar = new Car() { Id = id, Brand = car.Brand, ModelName = car.ModelName, Year = car.Year }; return(_carsRepo.Update(editedCar)); }
public async Task CreateAsync(CreateCarViewModel model) { var car = AutoMapperConfig.MapperInstance.Map <Car>(model); car.Id = Guid.NewGuid().ToString(); await this.carsRepository.AddAsync(car); await this.carsRepository.SaveChangesAsync(); }
public async Task <ActionResult> CreateCar(CreateCarViewModel newCarViewModel) { if (ModelState.IsValid) { string carId = Guid.NewGuid().ToString(); Car car = new Car() { Id = carId, Name = $"{newCarViewModel.Make} {newCarViewModel.Model}", TrackId = newCarViewModel.TrackId }; string carsImagesPath = HttpContext.Server.MapPath("~/Content/Images/Cars"); bool fileNotFound = true; // Add uploaded image if selected, or use default if (Request.Files.Count > 0) { var postedFile = Request.Files[0]; if (postedFile != null && postedFile.ContentLength > 0) { fileNotFound = false; string extension = Path.GetExtension(postedFile.FileName); string carFileName = $"{carId}{extension}"; car.ImageName = carFileName; string saveToPath = Path.Combine(carsImagesPath, carFileName); postedFile.SaveAs(saveToPath); } } if (fileNotFound) { var defaultCarFileToUsePath = Path.Combine(carsImagesPath, "0.jpg"); if (System.IO.File.Exists(defaultCarFileToUsePath)) { string defaultCarImageWithUniqueCarId = $"{carId}.jpg"; car.ImageName = defaultCarImageWithUniqueCarId; string defaultSaveToPath = Path.Combine(carsImagesPath, defaultCarImageWithUniqueCarId); byte[] bytes = System.IO.File.ReadAllBytes(defaultCarFileToUsePath); System.IO.File.WriteAllBytes(defaultSaveToPath, bytes); } } try { CarsRepository <Car, CarDTO> carsRepo = new CarsRepository <Car, CarDTO>(); car = await carsRepo.Insert(car); TempData["CarId"] = car.Id; } catch (Exception) { ModelState.AddModelError(string.Empty, "Failed to save new car."); } } return(RedirectToAction("Index")); }
public ViewResult AddNewCar(string category) { _logger.LogInformation($"LOG View to creationg car"); CreateCarViewModel obj = new CreateCarViewModel(); obj.categoryName = category; return(View(obj)); }
public IActionResult Post(CreateCarViewModel createCarViewModel) { if (ModelState.IsValid) { Car car = _carService.Add(createCarViewModel); return(Created("URI to car omitted", car)); } return(BadRequest(createCarViewModel)); }
public async Task <IActionResult> Create(CreateCarViewModel carModel) { if (!this.ModelState.IsValid) { return(this.View(carModel)); } await this.carsService.CreateAsync(carModel); return(this.RedirectToAction("MyCars")); }
public async Task <IActionResult> Create(CreateCarViewModel form) { var newCar = _allCars.CreateCar(form); await _hubContext.Clients.All.SendAsync("needUpdateCars", newCar); _logger.LogInformation($"LOG Creatind new car Model; Sending hubs"); // await Task.Delay(1000); return(Redirect("/Home/Index")); }
public IActionResult Create(CreateCarViewModel carViewModel) { if (ModelState.IsValid) { _carService.Add(carViewModel); return(RedirectToAction(nameof(Index))); } return(View(carViewModel)); }
public Car Edit(int id, CreateCarViewModel car) { Car editedCar = FindBy(id); editedCar.ModelName = car.ModelName; editedCar.Brand = car.Brand; editedCar.Year = car.Year; editedCar.Insurances = car.Insurances; return(_carsRepo.Update(editedCar)); }
public IActionResult AjaxCreateForm(CreateCarViewModel carViewModel) { if (ModelState.IsValid) { Car car = _carService.Add(carViewModel); return(PartialView("_CarPartialView", car)); } Response.StatusCode = 400; return(PartialView("_CarCreateAjaxPartialView", carViewModel)); }
public ActionResult Create() { var car = new CreateCarViewModel(); car.Owner = LoginSession.Current.UserID; var models = modelsRepo.GetAll(); ViewBag.Models = new SelectList(models, "ID", "Name"); return(View(car)); }
// GET: Cars/Create public IActionResult Create() { CreateCarViewModel model = new CreateCarViewModel(); model.Marcas = _context.Marca.Select(marca => new SelectListItem() { Value = marca.Id.ToString(), Text = marca.Nombre.ToString() }) .ToList(); return(View(model)); }
public IActionResult Create(CreateCarViewModel modelvm) { if (ModelState.IsValid) { int id_cl = _context.FindUser(User.Identity.Name).id_client.Value; int id_supp = _context.FindSupplierByClient(id_cl).Id; Car car = new Car() { Mark = modelvm.Mark, Model = modelvm.Model, Color = modelvm.Color, Goverment_number = modelvm.Goverment_number, Year = modelvm.Year, id_supplier = id_supp, Price = modelvm.Price, status = "Свободен", country = modelvm.country, city = modelvm.city, Image = null, ImageMimeType = null, }; if (modelvm.Image != null) { byte[] imageData = null; using (var binaryReader = new BinaryReader(modelvm.Image.OpenReadStream())) { imageData = binaryReader.ReadBytes((int)modelvm.Image.Length); } car.Image = Convert.ToBase64String(imageData);; car.ImageMimeType = modelvm.Image.ContentType; } if (_context.AddCar(car)) { return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "Ошибка"); } } else { ModelState.AddModelError("", "Ошибка"); } if (AllMarks[0] == "Все") { AllMarks.RemoveAt(0); } ViewBag.Marks = new SelectList(AllMarks); return(View(modelvm)); }
public ActionResult Create(CreateCarViewModel modelView) { var model = new DataAccess.Car(); model.Color = modelView.Color; model.Year = modelView.Year; model.Owner = modelView.Owner; model.Model = modelView.Model; model.HorsePower = modelView.HorsePower; repo.Create(model); return(RedirectToAction("Index")); }
public async Task <IActionResult> CreateCar(CreateCarViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var carDetails = _mapper.Map <CarDetails>(model); var car = _mapper.Map <Car>(model); await _carService.AddCarAndDetails(car, carDetails); return(LocalRedirect("/cars")); }
public IActionResult Put(int id, [FromBody] CreateCarViewModel carViewModel) { if (ModelState.IsValid) { Car car = _carService.Edit(id, carViewModel); if (car == null) { return(Problem("Unable to save changes.", null, 500)); } return(Ok(car)); } return(BadRequest(carViewModel)); }
public async Task <IActionResult> Create(CreateCarViewModel createCarViewModel) { try { var mapper = new MapperConfiguration(cfg => cfg.CreateMap <CarDTO, CreateCarViewModel>()).CreateMapper(); var carDto = mapper.Map <CreateCarViewModel, CarDTO>(createCarViewModel); await _carService.CreateAsync(carDto); return(RedirectToAction(nameof(Create))); } catch { return(View()); } }
public async Task <IActionResult> CreateCar(CreateCarViewModel model) { if (ModelState.IsValid) { var userId = userManager.GetUserId(HttpContext.User); Cars entry = new Cars() { FullName = model.FullName, Description = model.Description, Price = model.Price, ProdDate = model.ProdDate, Location = model.Location, SiteUserId = userId }; _context.Add(entry); await _context.SaveChangesAsync(); if (model.UploadedFile != null) { var getEntry = await _context.Cars.Where(s => s.FullName.Equals(model.FullName) && s.SiteUserId == entry.SiteUserId && s.Description.Equals(entry.Description)) .FirstOrDefaultAsync(); string partialPath = Path.Combine(hostEnvironment.WebRootPath + "/images/"); string uniqueName = Guid.NewGuid().ToString() + model.UploadedFile.FileName; string fullPather = Path.Combine(partialPath + uniqueName); using (var filestream = new FileStream(fullPather, FileMode.Create)) { model.UploadedFile.CopyTo(filestream); } CarImage entryImage = new CarImage() { filePath = "~/images/" + uniqueName, carId = getEntry.Id, fullPath = uniqueName }; _context.Add(entryImage); await _context.SaveChangesAsync(); return(RedirectToAction("ListEntries", "UserManagement")); } else { return(RedirectToAction("ListEntries", "UserManagement")); } } return(View(model)); }
private string ProcessUploadFile(CreateCarViewModel model) { string uniqueFileName = null; if (model.Photo != null) { string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images"); uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { model.Photo.CopyTo(fileStream); } } return(uniqueFileName); }
public async Task <IActionResult> Cars(CreateCarViewModel model) { IdentityUser user = await _userManager.FindByNameAsync(HttpContext.User.Identity.Name); var addRecord = new Car { Color = _context.Colours.Where(x => x.Id == int.Parse(model.SelectedColour)).First(), Condition = _context.Conditions.Where(x => x.Id == int.Parse(model.SelectedCondition)).First(), User = user, Price = model.Price }; await _carService.AddCar(addRecord); var vm = await CreateVM(); return(View(vm)); }
public CreateCarViewModel initializeCarModel() { string jsonText = null; // read Json File, deserialize it to List<string> using (var reader = new StreamReader(carModelsJsonPath)) { jsonText = reader.ReadToEnd(); }; var carModels = JsonConvert.DeserializeObject <List <CarType> >(jsonText); var types = new SelectList(carModels.Select(m => m.type)); var renderModel = new CreateCarViewModel(); renderModel.CarTypes = types; renderModel.ProductAge = DateTime.Today; return(renderModel); }
public async Task <IActionResult> CreateNewCar([FromBody] CreateCarViewModel carData) { try { if (!ModelState.IsValid) { return(Json(new { IsSuccess = false, Message = "Parameter can not be null" })); } bool result = await _carService.AddNewCar(carData); return(Json(new { IsSuccess = true, Message = "Car Added Successfully" })); } catch (ApplicationException e) { return(Json(new { IsSuccess = false, e.Message })); } }