public void MapFrom(Entities.Product e, ref Models.ProductModel m) { m.Id = e.Id; m.UserId = e.UserId; m.Transaction_Type = e.Transaction_Type; m.Product_Type = e.Product_Type; m.CityId = e.CityId; m.DistrictId = e.DistrictId; m.WardId = e.WardId; m.Text = e.Text; m.Text_Alias = e.Text_Alias; m.HouseNumber = e.HouseNumber; m.Address = e.Address; m.Area = e.Area; m.Description = e.Description; m.StandardCost = StringHelperExtension.MoneyExchange(e.StandardCost, '/'); m.SellStartDate = e.SellEndDate; m.SellEndDate = e.SellEndDate; m.State = e.State; m.AgencyCost = e.AgencyCost; m.CostUnit = e.CostUnit; m.Tag = e.Tag; m.Approval_Flag = e.Approval_Flag; m.ApprovalBy = e.ApprovalBy; m.ApprovalDate = e.ApprovalDate; m.Delete_Flag = e.Delete_Flag; m.DeleteBy = e.DeleteBy; m.DeleteDate = e.DeleteDate; m.Avatar = e.Avatar; m.Avatar_Url = e.Avatar_Url; m.UpdateBy = e.UpdateBy.GetValueOrDefault(); m.UserName = e.UserName; m.RoleId = e.RoleId.GetValueOrDefault(); m.RoleText = e.RoleText; }
public ActionResult ProductModification(int id) { if (Session["Login"] != null && Session["Company"] != null) { gelen = (AppUsers)Session["Login"]; companybilgi = (Company)Session["Company"]; } else { return(RedirectToAction("Index", "Home", new { area = "" })); } if (productManagement.GetProductById(id) != null && companybilgi.Products.Where(s => s.ProductID == id).Count() > 0) { if (gelen.Status.Value == 2) { StockManagement.Areas.Admin.Models.ProductModel productModel = new Models.ProductModel(); productModel.cargo = cargoManagement.getAllCargo(); productModel.categories = categoryManagement.GetAllCategory(); productModel.storage = storageManagement.getAllCompanyStorage(companybilgi.CompanyID); productModel.product = productManagement.GetProductById(id); Session["hata"] = productModel.product.ProductID; return(View(productModel)); } else { return(RedirectToAction("Index", "Admin")); } } else { return(RedirectToAction("Index", "Admin")); } }
// GET: Product/Edit/5 public ActionResult Edit(int id) { Models.ProductModel productModel = new Models.ProductModel(); DataTable dtblProduct = new DataTable(); using (MySqlConnection con = new MySqlConnection(connectionString)) { con.Open(); String query = "SELECT * FROM products WHERE productId = @ProductID"; MySqlDataAdapter mySqlDa = new MySqlDataAdapter(query, con); mySqlDa.SelectCommand.Parameters.AddWithValue("@ProductID", id); mySqlDa.Fill(dtblProduct); } if (dtblProduct.Rows.Count == 1) { productModel.ProductID = Convert.ToInt32(dtblProduct.Rows[0][0].ToString()); productModel.ProductName = dtblProduct.Rows[0][1].ToString(); productModel.Price = Convert.ToDecimal(dtblProduct.Rows[0][2].ToString()); productModel.Stock = Convert.ToInt32(dtblProduct.Rows[0][3].ToString()); return(View(productModel)); } else { return(RedirectToAction("index")); } }
public IHttpActionResult AddItem(Guid basketId, [FromBody] Models.ProductModel product) { try { if (product == null || !ModelState.IsValid) { return(BadRequest()); } // var newProduct = _product.CreateProduct(); // newProduct.ProductId = Guid.NewGuid(); newProduct.Name = product.Name; newProduct.Description = product.Description; newProduct.Quantity = product.Quantity; newProduct.Price = product.Price; // var updatedBasket = _basketLogic.AddProducts(basketId, newProduct); if (updatedBasket == null) { return(BadRequest()); } return(Ok(updatedBasket)); } catch (Exception ex) { return(BadRequest()); } }
} // Điện thoại người đăng public void MapFrom(Entities.Product e, ref Models.ProductModel m) { m.Id = e.Id; m.UserId = e.UserId; m.Transaction_Type = e.Transaction_Type; m.Product_Type = e.Product_Type; m.CityId = e.CityId; m.CityText = e.CityText; m.DistrictId = e.DistrictId; m.DistrictText = e.DistrictText; m.WardId = e.WardId; m.Text = e.Text; m.HouseNumber = e.HouseNumber; m.Address = e.Address; m.Area = e.Area; m.Description = e.Description; m.StandardCost = e.StandardCost; m.SellStartDate = e.SellEndDate; m.SellEndDate = e.SellEndDate; m.State = e.State; m.AgencyCost = e.AgencyCost; m.CostUnit = e.CostUnit; m.Tag = e.Tag; m.Approval_Flag = e.Approval_Flag; m.ApprovalBy = e.ApprovalBy; m.ApprovalDate = e.ApprovalDate; m.Delete_Flag = e.Delete_Flag; m.DeleteBy = e.DeleteBy; m.DeleteDate = e.DeleteDate; m.Avatar = e.Avatar; m.Avatar_Url = e.Avatar_Url; m.UpdateCost = e.UpdateCost; m.UpdateBy = e.UpdateBy; m.UpdateTime = e.UpdateTime; }
public void AddNewProduct(Models.ProductModel product) { using (var db = GetDbConnection()) { db.Product.Add(Mapper.Map <ProductModel, Product>(product)); db.SaveChanges(); } }
public ActionResult Manage(Models.ProductModel product) { if (ModelState.IsValid || product.Mode == "D") { product.Save(); return(PartialView("_Product")); } product.LoadSelectLists(); return(PartialView("_Manage", product)); }
public static ProductEntity Load(Models.ProductModel model) { return(new ProductEntity() { Name = model.Name, Price = model.Price, Quantity = model.Quantity, PartitionKey = Partition, RowKey = model.Id, }); }
public static ProductModel MapClientToServer(this Models.ProductModel source) { return(new ProductModel { ProductModelID = source.ProductModelId, ProductId = source.ProductId, ModelName = source.ModelName, ModelDescription = source.ModelDescription, Price = source.Price }); }
private void FillPage(int id) { Models.ProductModel productmodel = new Models.ProductModel(); Product product = productmodel.GetProduct(id); txtDescription.Text = product.Description; txtName.Text = product.Name; txtPrice.Text = product.Price.ToString(); ddlImage.SelectedValue = product.Image; ddlType.SelectedValue = product.TypeID.ToString(); }
public static ProductViewModel ToProductViewModel(this Models.ProductModel model) { return(new ProductViewModel() { Id = model.ID, Description = model.Description, Name = model.Name, Owner = model.Owner.ToUserDataViewModel(), PartNumber = model.PartNo, Price = model.Price, Identifier = model.ProductIdentifier, ImageUrl = model.ImageUrl }); }
public Models.ProductModel CreateProduct(Models.ProductModel model) { using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.connecString(db))) { var product = new DynamicParameters(); product.Add("@productCode", model.product_code); product.Add("@productName", model.product_name); product.Add("@productStatus", model.product_status); product.Add("@id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("dbo.spProduct_Insert", product, commandType: CommandType.StoredProcedure); model.id = product.Get <int>("id"); return(model); } }
public ActionResult Create(Models.ProductModel productModel) { // TODO: Add insert logic here using (MySqlConnection mysqlCon = new MySqlConnection(connectionString)) { mysqlCon.Open(); String insertQry = "INSERT INTO products(productName,price,stock)VALUES(@ProductName,@Price,@Stock)"; MySqlCommand mySqlcmd = new MySqlCommand(insertQry, mysqlCon); mySqlcmd.Parameters.AddWithValue("@ProductName", productModel.ProductName); mySqlcmd.Parameters.AddWithValue("@Price", productModel.Price); mySqlcmd.Parameters.AddWithValue("@Stock", productModel.Stock); mySqlcmd.ExecuteNonQuery(); } return(RedirectToAction("Index")); }
protected void btnSubmit_Click(object sender, EventArgs e) { Models.ProductModel productModel = new Models.ProductModel(); Product product = CreateProduct(); if (!String.IsNullOrWhiteSpace(Request.QueryString["id"])) { int id = Convert.ToInt32(Request.QueryString["id"]); lblResult.Text = productModel.UpdateProduct(id, product); } else { lblResult.Text = productModel.InsertProduct(product); } }
public ActionResult Edit(Models.ProductModel productModel) { using (MySqlConnection SqlCon = new MySqlConnection(connectionString)) { SqlCon.Open(); String query = "UPDATE products SET productName = @ProductName , Price = @Price , stock = @Stock WHERE productId = @ProductID"; MySqlCommand sqlCmd = new MySqlCommand(query, SqlCon); sqlCmd.Parameters.AddWithValue("@ProductID", productModel.ProductID); sqlCmd.Parameters.AddWithValue("@ProductName", productModel.ProductName); sqlCmd.Parameters.AddWithValue("@Price", productModel.Price); sqlCmd.Parameters.AddWithValue("@Stock", productModel.Stock); sqlCmd.ExecuteNonQuery(); } return(RedirectToAction("Index")); }
public ActionResult Create(Models.ProductModel productModel) { if (ModelState.IsValid) { var createModel = new Models.ProductModel(); createModel.ProdName = productModel.ProdName; createModel.Price = productModel.Price; createModel.Count = productModel.Count; createModel.ImagePath = productModel.ImagePath; createModel.ProdDescription = productModel.ProdDescription; createModel.BuildDateTime = DateTime.Now; this._DBContent.Products.Add(createModel); this._DBContent.SaveChanges(); return(RedirectToAction("Deatils")); } return(View("Index")); }
public ActionResult Edit(int id, FormCollection collection) { try { Models.ProductModel productModel = new Models.ProductModel(); UpdateModel(productModel); productRepository.UpdateProduct(productModel); return(RedirectToAction("Index")); } catch (Exception ex) { HandleErrorInfo error = new HandleErrorInfo(ex, "Product", "Edit"); return(View("Error", error)); } }
//GET: api/product public IHttpActionResult GetAllProducts() { using (SalesDBEntities db = new SalesDBEntities()) { var productsFromDB = db.Products.ToList(); List <Models.ProductModel> product = new List <Models.ProductModel>(); foreach (var item in productsFromDB) { Models.ProductModel model = new Models.ProductModel(); model.ProductID = item.ProductID; model.Name = item.Name; model.Price = item.Price; product.Add(model); } return(Ok(product)); } }
public async Task <IActionResult> OnPostAddToCartAsync(string productId) { Models.ProductModel product = await _catalogApi.GetProduct(productId); string username = "******"; BasketModel basket = await _basketApi.GetBasket(username); basket.Items.Add(new BasketItemModel { ProductId = productId, ProductName = product.Name, Price = product.Price, Quantity = 1, Color = "Black" }); basket = await _basketApi.CreateBasket(basket); return(RedirectToPage("Cart")); }
private void FillPage() { if (!String.IsNullOrWhiteSpace(Request.QueryString["id"])) { int id = Convert.ToInt32(Request.QueryString["id"]); Models.ProductModel productModel = new Models.ProductModel(); WebApplication1.Product product = productModel.GetProduct(id); lblPrice.Text = "Price per unit: <br/>$ " + product.Price; lblTitle.Text = product.Name; lblDescription.Text = product.Description; lblItemNr.Text = id.ToString(); imgProduct.ImageUrl = "~/Images/Products/" + product.Image; int[] amount = Enumerable.Range(1, 20).ToArray(); ddlAmount.DataSource = amount; ddlAmount.AppendDataBoundItems = true; ddlAmount.DataBind(); } }
public Microsoft.AspNetCore.Mvc.IActionResult Learn02() { var model = new System.Collections.Generic.List <Models.ProductModel>(); for (int index = 1; index < 25; index++) { Models.ProductModel productModel = new Models.ProductModel { Name = $"Product #{index}", UnitPrice = 18 + index, UnitsInStock = 56 + index, Discontinued = (index % 2 == 0 ? true : false), Status = (index % 2 == 0 ? "Fail" : "Success"), }; model.Add(productModel); } return(View(model: model)); }
public static System.Collections.Generic.List <Models.ProductModel> GetProducts(int n) { var model = new System.Collections.Generic.List <Models.ProductModel>(); for (int index = 1; index <= n; index++) { Models.ProductModel productModel = new Models.ProductModel { Name = $"Product #{index}", UnitPrice = 18 + index, UnitsInStock = 56 + index, Discontinued = (index % 2 == 0 ? true : false), Status = (index % 2 == 0 ? "Fail" : "Success"), }; model.Add(productModel); } return(model); }
public ActionResult Edit(Models.ProductModel model, HttpPostedFileBase file) { if (ModelState.IsValid) { string fileName = string.Empty; string filePath = string.Empty; if (file != null && file.ContentLength > 0) { fileName = System.IO.Path.GetFileName(file.FileName); filePath = System.IO.Path.Combine(Server.MapPath("~/FileUploads"), fileName); } try { var resultModel = this._DBContent.Products.Find(model.ID); resultModel.ProdName = model.ProdName; resultModel.Price = model.Price; var strPath = $"/FileUploads/{fileName}"; if (!(string.IsNullOrEmpty(fileName)) && resultModel.ImagePath != strPath) { file.SaveAs(filePath); resultModel.ImagePath = strPath; model.ImagePath = strPath; } resultModel.Count = model.Count; resultModel.ProdDescription = model.ProdDescription; resultModel.BuildDateTime = DateTime.Now; this._DBContent.SaveChanges(); ViewBag.msg = "儲存成功。"; } catch { //Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; //return Content("找不到產品"); } } return(View("Edit", model)); }
/// <summary> /// Cập nhật sản phẩm cho thuê /// </summary> /// <param name="Id"></param> /// <returns></returns> public ActionResult UpdateLeaseProduct(int Id) { ViewBag.ActionSubMenu = "Lease"; // Kiểm tra quyền đăng bài Entities.Item role = new Entities.Item(); int result = CheckRolePost(ref role); if (result < 0) { return(Redirect(result)); } Models.ProductModel model = new Models.ProductModel(); if (Id > 0) { Entities.Product e = productService.GetById(Id); model.MapFrom(e, ref model); } else { // set default. model.SellStartDate = DateTime.Now; model.SellEndDate = DateTime.Now.AddMonths(1); model.UserId = int.Parse(CookieHelper.Get(AdminConfigs.COOKIES_USER_ID)); model.UserName = CookieHelper.Get(AdminConfigs.COOKIES_USERNAME); } LoadModel(ref model); // Add list product List <Entities.Product> lstEntity = productService.List(); ViewBag.ListProduct = lstEntity; ViewBag.NumberItem = lstEntity.Count; ViewBag.ActionForm = "UpdateLeaseProduct"; ViewBag.SubmitValue = Id > 0 ? AdminConfigs.BUTTON_UPDATE : AdminConfigs.BUTTON_POST_NEW; return(PartialView("Index", model)); }
public void MapFrom(Models.ProductModel m, ref Entities.Product e) { e.Id = m.Id; e.UserId = m.UserId; e.Transaction_Type = m.Transaction_Type; e.Product_Type = m.Product_Type; e.CityId = m.CityId; e.DistrictId = m.DistrictId; e.WardId = m.WardId; e.Text = m.Text; e.Text_Alias = m.Text.ToAlias(); e.HouseNumber = m.HouseNumber; e.Address = m.Address; e.Area = m.Area; e.Description = m.Description; e.StandardCost = m.StandardCost; e.SellStartDate = m.SellEndDate; e.SellEndDate = m.SellEndDate; e.State = m.State; e.AgencyCost = m.AgencyCost; e.CostUnit = m.CostUnit; e.Tag = m.Tag; e.Approval_Flag = m.Approval_Flag; e.ApprovalBy = m.ApprovalBy; e.ApprovalDate = m.ApprovalDate; e.Delete_Flag = m.Delete_Flag; e.DeleteBy = m.DeleteBy; e.DeleteDate = m.DeleteDate; e.Avatar = m.Avatar; e.Avatar_Url = m.Avatar_Url; e.UpdateCost = m.StandardCost; e.UpdateTime = DateTime.Now; e.UpdateBy = m.UpdateBy; e.UserName = m.UserName; e.RoleId = m.RoleId; e.RoleText = m.RoleText; }
public ActionResult Edit(int id) { Models.ProductModel productModel = productRepository.GetProductById(id); return(View("EditProduct", productModel)); }
protected void btnSubmit_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string longSize = "", wideSize = "", heightSize = "", frontWideSize = "", backWideSize = ""; int flag = 0; for (int i = 0; i < txtSize.Text.Length; i++) { if (flag == 0) { if (txtSize.Text[i] != 'x') { longSize += txtSize.Text[i]; } else { flag = 1; continue; } } if (flag == 1) { if (txtSize.Text[i] != 'x') { wideSize += txtSize.Text[i]; } else { flag = 2; continue; } } if (flag == 2) { heightSize += txtSize.Text[i]; } } flag = 0; for (int i = 0; i < txtLength.Text.Length; i++) { if (flag == 0) { if (txtLength.Text[i] != 'x') { frontWideSize += txtLength.Text[i]; } else { flag = 1; continue; } } if (flag == 1) { backWideSize += txtLength.Text[i]; } } string sTenfile = FileUpload1.FileName; Models.ProductModel productOb = new Models.ProductModel(); productOb.ProductName = txtProductName.Text; productOb.CountryMade = txtXuatXu.Text; productOb.YearMade = int.Parse(txtNamSX.Text); productOb.Price = txtGiaBan.Text; productOb.Amount = int.Parse(txtAmount.Text); productOb.CatId = int.Parse(ddlCarCat.SelectedValue); productOb.Used = ddlStatus.SelectedIndex == 0 ? false : true; productOb.MileAge = productOb.Used == false ? 0 : int.Parse(txtRunMile.Text); productOb.Long = float.Parse(longSize); productOb.Wide = float.Parse(wideSize); productOb.Height = float.Parse(heightSize); productOb.FrontWideWheelbase = float.Parse(frontWideSize); productOb.BackWideWheelbase = float.Parse(backWideSize); productOb.WeightNonLoad = float.Parse(txtHeavy.Text); productOb.NumberCapacity = int.Parse(txtSeat.Text); productOb.EngineenType = txtEngineenType.Text; productOb.CylinderCapacity = float.Parse(txtXiLanh.Text); productOb.MaximumPower = txtMaxPower.Text; productOb.MaximumTorque = txtMomen.Text; productOb.GasCapacity = float.Parse(txtFuel.Text); productOb.PowerSteering = txtGiamXoc.Text; productOb.GasConsumptionAvg = float.Parse(txtNhienLieu.Text); productOb.NumberOfColor = int.Parse(txtColor.Text); productOb.DayLight = txtDayLight.Text; productOb.LightSensor = txtLightSensor.Text; productOb.FogLight = txtFogLight.Text; productOb.WashLight = txtLightWash.Text; productOb.WheelSize = float.Parse(txtWheelSize.Text); productOb.SitMaterial = txtSeatMaterial.Text; productOb.Camera = int.Parse(txtCamera.Text); productOb.LongWheelbase = int.Parse(txtLongWheel.Text); productOb.ProductImage = sTenfile; productDL.AddProduct(productOb, userDL.GetUserID(username)); FileUpload1.SaveAs(Server.MapPath("~/Images/") + sTenfile); Response.Redirect("Product.aspx"); } else { Response.Write("<script>alert('Product image is required.')</script>"); } }
public void LoadModel(ref Models.ProductModel m) { PlaceService placeService = new PlaceService(); RegionService regionService = new RegionService(); UserInRolesService userInRoleService = new UserInRolesService(); // Xử lý lấy ID tỉnh, thành phố; quận, huyện. // Trường hợp có Xã, phường //if (m.PlaceId > 0) //{ // var temp = placeService.GetParentItem(m.PlaceId); // m.DistrictId = temp.Id; // temp = placeService.GetParentItem(m.DistrictId); // m.CityId = temp.Id; //} // Danh sách kiểu nhà m.ListProductType = productService.ListProductType(); // Danh sách tỉnh m.ListCity = placeService.ListPlaceItemByParent(0); if (m.CityId > 0) { m.ListDistrict = placeService.ListPlaceItemByParent(m.CityId); } else { m.ListDistrict = new List <Entities.Item>(); } // Lấy danh sách quận huyện if (m.DistrictId > 0) { m.ListWard = placeService.ListPlaceItemByParent(m.DistrictId); } else { m.ListWard = new List <Entities.Item>(); } // Lấy đơn vị tính. m.ListCostUnit = productService.ListCostUnit(); List <Entities.Item> lstRegion = regionService.ListItemActive(); int id = m.Id; if (id > 0) { // Lấy thông tin vùng cố định var fixedRegion = regionService.GetFixedRegion(m.WardId); if (fixedRegion != null) { m.regionFixedId = fixedRegion.Id; m.regionFixedText = fixedRegion.Text; } // Lấy danh sách ảnh var lstImg = productService.GetListImage(id); m.ListImage = lstImg.Select(x => Url.Content(x.ImageUrl + "\\" + x.Text)).ToArray(); string username = m.UserName; var imgConfig = lstImg.Select(y => new Models.ImageConfig() { caption = y.Text, size = y.Size, key = y.Text, url = @Url.Action("DeleteImage", "Product", new { image = y.Text, productId = id, username = username }) } ).ToArray(); m.LstImageConfig = imgConfig; // Lấy thông tin vùng lân cận. List <int> regionIds = new List <int>(); regionIds.Add(m.regionFixedId); lstRegion = RegionSelected(m.regionFixedId, id, ref regionIds, m.CityId); // Lấy chuỗi các xã phường tương ứng. //m.StrWards = StringPlaceByRegions(regionIds); // Lấy hướng dẫn chi phí cho môi giới switch (m.CostUnit) { case 1: m.StrTutrialCostUnit = AdminConfigs.TUTORIAL_PERCEN_HOUSE; break; default: break; } } else { // Lấy thông tin vùng cố định m.regionFixedId = 0; // Lấy thời gian bán mặc định. m.SellStartDate = System.DateTime.Now; // Lấy danh sách ảnh. m.ListImage = GetAllFileTemp(m.UserName); m.LstImageConfig = GetAllFileInfo(id, ImageType.PRODUCT_TEMP, m.UserName); m.StrTutrialCostUnit = AdminConfigs.TUTORIAL_PERCEN_HOUSE; } // Lấy danh sách vùng. m.ListRegion = lstRegion; // Kiểm tra xem người đăng có phải môi giới không. m.IsAgency = userInRoleService.CheckUserIsAgency(m.UserId); // Lấy danh sách vùng gửi cố định theo user. m.ListFixedSendRegion = uirService.GetListItemByUser(m.UserId, 1); // Lấy danh sách xã, phường theo vùng cố định khi chọn địa chỉ. List <int> regionByAddress = new List <int>(); if (m.regionFixedId > 0) { m.StrWards2 = StringPlaceByRegions(m.regionFixedId); } // Lấy danh sách xã, phường theo vùng cố định theo quyền môi giới. foreach (var item in m.ListFixedSendRegion) { regionByAddress.Add(item.Id); } m.StrWards1 = StringPlaceByRegions(regionByAddress); }
public ActionResult ShowManageScreen(Models.ModelRequest productRequest) { Models.ProductModel product = new Models.ProductModel(productRequest); return(PartialView("_Manage", product)); }
public ActionResult UpdateLeaseProduct(int id, Models.ProductModel model, int[] ListRegionNeighbor) { ViewBag.ActionSubMenu = "Lease"; bool isSuccess = false; int newId = 0; // Kiểm tra quyền đăng bài Entities.Item role = new Entities.Item(); int roleId = CheckRolePost(ref role); if (roleId < 0) { Logs.LogWrite("UpdateLeaseProduct Kiểm tra quyền đăng"); return(Redirect(roleId)); } if (ModelState.IsValid) { Entities.Product e = new Entities.Product(); model.Id = id; model.Transaction_Type = (int)Enums.TransactionType.CHO_THUE; // nhà cho thuê model.UserId = int.Parse(CookieHelper.Get(AdminConfigs.COOKIES_USER_ID)); // Chuyển tiền thành triệu. model.StandardCost = StringHelperExtension.MoneyExchange(model.StandardCost); model.MapFrom(model, ref e); if (id <= 0) { e.UpdateBy = e.UserId; // Lấy thông tin username e.UserName = CookieHelper.Get(AdminConfigs.COOKIES_USERNAME); // Lấy thông tin role. e.RoleId = role.Id; e.RoleText = role.Text; } int result = 0; result = productService.Save(e); if (result < 0) { ViewBag.Message = AdminConfigs.MESSAGE_UPDATE_ERROR; ViewBag.AlertClass = AdminConfigs.CLASS_ALERT_DANGER; TempData[AdminConfigs.TEMP_MESSAGE] = AdminConfigs.MESSAGE_UPDATE_ERROR; } else { newId = result; #region Xử lý thêm ảnh vào database Models.ImageConfig[] arrImg = GetAllFileInfo(id, ImageType.PRODUCT_TEMP, e.UserName); if (arrImg.Count() > 0) { string sourceFolder = AdminConfigs.PHYSICAL_PATH + CookieHelper.Get(AdminConfigs.COOKIES_USERNAME).ToLower() + AdminConfigs.DIRSEPARATOR + AdminConfigs.FOLDER_PRODUCT_TEMPS; string targetFolder = AdminConfigs.PHYSICAL_PATH + CookieHelper.Get(AdminConfigs.COOKIES_USERNAME).ToLower() + AdminConfigs.DIRSEPARATOR + AdminConfigs.FOLDER_PRODUCTS; string urlImg = AdminConfigs.IMAGE_PATH + CookieHelper.Get(AdminConfigs.COOKIES_USERNAME).ToLower() + AdminConfigs.ALTDIRECTORYSEPARATORCHAR + AdminConfigs.FOLDER_PRODUCTS + AdminConfigs.ALTDIRECTORYSEPARATORCHAR; string urlImgTemp = AdminConfigs.IMAGE_PATH + CookieHelper.Get(AdminConfigs.COOKIES_USERNAME).ToLower() + AdminConfigs.ALTDIRECTORYSEPARATORCHAR + AdminConfigs.FOLDER_PRODUCT_TEMPS + AdminConfigs.ALTDIRECTORYSEPARATORCHAR; try { // Cập nhật avatar productService.UpdateAvatar(result, arrImg[0].caption, urlImg + AdminConfigs.AVATAR_WIDTH + "_" + AdminConfigs.AVATAR_HEIGHT + AdminConfigs.ALTDIRECTORYSEPARATORCHAR); // Cập nhật tất cả ảnh vào DB Entities.ProductImage pi; foreach (Models.ImageConfig img in arrImg) { pi = new Entities.ProductImage(); pi.ProductId = result; pi.Text = img.caption; pi.Size = img.size; pi.ImageUrl = urlImg; pi.DateUpload = System.DateTime.Now; productService.Insert(pi); FileHelper.CropImage(Server.MapPath(Url.Content(urlImgTemp + img.caption))); } // Xử lý chuyển ảnh từ folder temp sang folder product. FileHelper.MoveFile(sourceFolder, targetFolder); } catch { } } #endregion #region Xử lý cập nhật danh sách Product - Region // Cập nhật vùng cố định. Entities.Product_Region pr; if (id == 0) { pr = new Entities.Product_Region(); // Insert pr.ProductId = result; pr.RegionId = model.regionFixedId; pr.Fixed = true; pr.Status = true; productService.Insert(pr); if (ListRegionNeighbor != null) { foreach (int regionId in ListRegionNeighbor) { pr = new Entities.Product_Region(); pr.ProductId = result; pr.RegionId = regionId; pr.Fixed = false; pr.Status = true; productService.Insert(pr); } } } else { // Update vùng cố định. int regionFixedDB = productService.GetRegionFixed(id); // Nếu đã tồn tại thì kiểm tra sự trùng khớp với regionFixedId if (regionFixedDB > 0) { // Nếu có sự khác thì cập nhật. if (regionFixedDB != model.regionFixedId) { pr = productService.GetProductRegion(id, regionFixedDB); pr.RegionId = model.regionFixedId; productService.Update(pr); } } // Cập nhật vùng lân cận. // 1. Lấy danh sách vùng lân cận theo product ID // 2. So sánh vùng lân cận đã lưu trong DB với vùng lân cận mới // + Nếu trong DB có mà danh sách mới không có thì update Status--> false. // + Nếu trong DB không có thì thêm mới. var listNeighborRegionDB = productService.ListNeighborRegion(id); if (listNeighborRegionDB != null) { foreach (Entities.Item item in listNeighborRegionDB) { if (!ListRegionNeighbor.Contains(item.Id)) { // Update status. pr = productService.GetProductRegion(id, item.Id); pr.Status = false; productService.Update(pr); } } foreach (int regionId in ListRegionNeighbor) { if (!listNeighborRegionDB.Exists(x => x.Id == regionId)) { // Add new pr = new Entities.Product_Region(); pr.ProductId = id; pr.RegionId = regionId; pr.Fixed = false; pr.Status = true; productService.Insert(pr); } else { // Update if status = false. pr = productService.GetProductRegion(id, regionId); if (pr.Status == false) { pr.Status = true; productService.Update(pr); } } } } else { foreach (int regionId in ListRegionNeighbor) { // Add new pr = new Entities.Product_Region(); pr.ProductId = id; pr.RegionId = regionId; pr.Fixed = false; pr.Status = true; productService.Insert(pr); } } } #endregion #region Xử lý gửi mail cho môi giới // Lấy thông tin host. Uri uri = Request.Url; string urlHost = uri.GetLeftPart(UriPartial.Authority); // Link sản phẩm. string link = "<a href='" + urlHost + "/" + AdminConfigs.FRIENDLY_LINK_PRODUCT_DETAIL.ToFriendlyUrl(result, e.Text.ToAlias()) + "'>" + e.Text + "</a>"; ArticleService articleService = new ArticleService(); Entities.Article article = new Entities.Article(); // Danh sách những email cần phải gửi thông tin. List <string> ListEmail = new List <string>(); // Lấy form mail từ bài viết article = articleService.GetByAlias("[email_thong_bao_san_pham_moi]"); // Xử lý các tham số trong mail. // Thay tên người bán article.Body = article.Body.Replace("[user]", e.UserName); // Thay tên sản phẩm article.Title = article.Title.Replace("[product]", e.Text); article.Body = article.Body.Replace("[product]", link); // Lấy danh sách email của các môi giới ListEmail = productService.ListEmailAgency(result); BusinessLayer.Helpers.MailHelper.MailArticle(article, ListEmail); #endregion TempData[AdminConfigs.TEMP_MESSAGE] = AdminConfigs.MESSAGE_UPDATE_SUCCESS; isSuccess = true; } } else { var errors = ModelState.Select(x => x.Value.Errors) .Where(y => y.Count > 0) .ToList(); ViewBag.Message = AdminConfigs.MESSAGE_UPDATE_ERROR; ViewBag.AlertClass = AdminConfigs.CLASS_ALERT_DANGER; } LoadModel(ref model); ViewBag.ActionForm = "UpdateLeaseProduct"; ViewBag.SubmitValue = id > 0 ? AdminConfigs.BUTTON_UPDATE : AdminConfigs.BUTTON_ADD; if (isSuccess) { //return RedirectToAction("Index", new { type = "", page = 1 }); return(RedirectToAction("Detail", "Template1", new { area = "", Id = newId })); } else { return(PartialView("Index", model)); } }