Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Move ContactUs methods to the new ContactController (from CommonController)
support3a73d07dbb47
diff --git a/src/Web/Grand.Web/Controllers/CommonController.cs b/src/Web/Grand.Web/Controllers/CommonController.csindex 019fe8c8f..4eb531da7 100644--- a/src/Web/Grand.Web/Controllers/CommonController.cs+++ b/src/Web/Grand.Web/Controllers/CommonController.cs@@ -2,23 +2,16 @@using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Common.Stores;-using Grand.Business.Core.Interfaces.Marketing.Contacts;-using Grand.Business.Core.Interfaces.Storage;-using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Localization;-using Grand.Domain.Media;using Grand.Domain.Stores;using Grand.Domain.Tax;using Grand.Infrastructure;using Grand.Infrastructure.Configuration;-using Grand.Web.Commands.Models.Common;using Grand.Web.Commands.Models.Customers;using Grand.Web.Common.Controllers;-using Grand.Web.Common.Extensions;using Grand.Web.Common.Filters;-using Grand.Web.Common.Security.Captcha;using Grand.Web.Common.Themes;using Grand.Web.Events;using Grand.Web.Features.Models.Common;@@ -34,28 +27,21 @@ namespace Grand.Web.Controllers{#region Fields- private readonly ITranslationService _translationService;private readonly ILanguageService _languageService;private readonly IWorkContext _workContext;private readonly IMediator _mediator;- private readonly CaptchaSettings _captchaSettings;#endregion#region Constructors- public CommonController(- ITranslationService translationService,- IWorkContext workContext,+ public CommonController(IWorkContext workContext,ILanguageService languageService,- IMediator mediator,- CaptchaSettings captchaSettings)+ IMediator mediator){- _translationService = translationService;_workContext = workContext;_languageService = languageService;_mediator = mediator;- _captchaSettings = captchaSettings;}#endregion@@ -147,10 +133,10 @@ namespace Grand.Web.Controllers[DenySystemAccount]public virtual async Task<IActionResult> SetLanguage([FromServices] AppConfig config,- string langcode, string returnUrl = default)+ string langCode, string returnUrl = default){- var language = await _languageService.GetLanguageByCode(langcode);+ var language = await _languageService.GetLanguageByCode(langCode);if (!language?.Published ?? false)language = _workContext.WorkingLanguage;@@ -179,7 +165,7 @@ namespace Grand.Web.Controllersreturn Redirect(returnUrl);}- //helper method to redirect (use in SlugRouteTransformer).+ //Use in SlugRouteTransformer.public virtual IActionResult InternalRedirect(string url, bool permanentRedirect){//ensure it's invoked from our GenericPathRoute class@@ -245,7 +231,7 @@ namespace Grand.Web.Controllers[PublicStore(true)]public virtual async Task<IActionResult> SetStore([FromServices] IStoreService storeService,- [FromServices] IStoreHelper _storeHelper,+ [FromServices] IStoreHelper storeHelper,[FromServices] CommonSettings commonSettings,string shortcut, string returnUrl = ""){@@ -257,7 +243,7 @@ namespace Grand.Web.Controllersvar selectedstore = storeService.GetAll().FirstOrDefault(x => string.Equals(x.Shortcut, shortcut, StringComparison.InvariantCultureIgnoreCase));if (selectedstore != null){- await _storeHelper.SetStoreCookie(selectedstore.Id);+ await storeHelper.SetStoreCookie(selectedstore.Id);//notificationawait _mediator.Publish(new ChangeStoreEvent(_workContext.CurrentCustomer, selectedstore));@@ -284,7 +270,7 @@ namespace Grand.Web.Controllers[DenySystemAccount]//available even when navigation is not allowed[PublicStore(true)]- public virtual async Task<IActionResult> SetTaxType(int customerTaxType, string returnUrl = "")+ public virtual async Task<IActionResult> SetTaxType(int customerTaxType, string returnUrl = default){var taxDisplayType = (TaxDisplayType)Enum.ToObject(typeof(TaxDisplayType), customerTaxType);await _workContext.SetTaxDisplayType(taxDisplayType);@@ -323,86 +309,6 @@ namespace Grand.Web.Controllersreturn Redirect(returnUrl);}- //contact us page- //available even when a store is closed- [ClosedStore(true)]- public virtual async Task<IActionResult> ContactUs(- [FromServices] StoreInformationSettings storeInformationSettings,- [FromServices] IPageService pageService)- {- if (storeInformationSettings.StoreClosed)- {- var closestorepage = await pageService.GetPageBySystemName("ContactUs");- if (closestorepage is not { AccessibleWhenStoreClosed: true })- return RedirectToRoute("StoreClosed");- }- var model = await _mediator.Send(new ContactUsCommand {- Customer = _workContext.CurrentCustomer,- Language = _workContext.WorkingLanguage,- Store = _workContext.CurrentStore- });- return View(model);- }-- [HttpPost, ActionName("ContactUs")]- [AutoValidateAntiforgeryToken]- [ValidateCaptcha]- [ClosedStore(true)]- [DenySystemAccount]- public virtual async Task<IActionResult> ContactUsSend(- [FromServices] StoreInformationSettings storeInformationSettings,- [FromServices] IPageService pageService,- ContactUsModel model, bool captchaValid)- {- if (storeInformationSettings.StoreClosed)- {- var closestorepage = await pageService.GetPageBySystemName("ContactUs");- if (closestorepage is not { AccessibleWhenStoreClosed: true })- return RedirectToRoute("StoreClosed");- }-- //validate CAPTCHA- if (_captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage && !captchaValid)- {- ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_translationService));- }-- if (ModelState.IsValid)- {- var result = await _mediator.Send(new ContactUsSendCommand {- CaptchaValid = captchaValid,- Model = model,- Store = _workContext.CurrentStore,- IpAddress = HttpContext?.Connection?.RemoteIpAddress?.ToString()- });-- if (result.errors.Any())- {- foreach (var item in result.errors)- {- ModelState.AddModelError("", item);- }- }- else- {- //notification- await _mediator.Publish(new ContactUsEvent(_workContext.CurrentCustomer, result.model));-- model = result.model;- return View(model);- }- }- var model1 = await _mediator.Send(new ContactUsCommand {- Customer = _workContext.CurrentCustomer,- Language = _workContext.WorkingLanguage,- Store = _workContext.CurrentStore,- Model = model- });-- return View(model1);- }--//sitemap pagepublic virtual async Task<IActionResult> Sitemap([FromServices] CommonSettings commonSettings){@@ -524,122 +430,6 @@ namespace Grand.Web.Controllersreturn View();}- [HttpPost]- [DenySystemAccount]- public virtual async Task<IActionResult> ContactAttributeChange(ContactAttributeChangeModel model)- {- var result = await _mediator.Send(new ContactAttributeChangeCommand {- Attributes = model.Attributes,- Customer = _workContext.CurrentCustomer,- Store = _workContext.CurrentStore- });- return Json(new- {- enabledattributeids = result.enabledAttributeIds.ToArray(),- disabledattributeids = result.disabledAttributeIds.ToArray()- });- }-- [HttpPost]- [DenySystemAccount]- public virtual async Task<IActionResult> UploadFileContactAttribute(string attributeId,- [FromServices] IDownloadService downloadService,- [FromServices] IContactAttributeService contactAttributeService)- {- var attribute = await contactAttributeService.GetContactAttributeById(attributeId);- if (attribute is not { AttributeControlType: AttributeControlType.FileUpload })- {- return Json(new- {- success = false,- downloadGuid = Guid.Empty- });- }- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFile = form.Files.FirstOrDefault();- if (httpPostedFile == null)- {- return Json(new- {- success = false,- message = "No file uploaded",- downloadGuid = Guid.Empty- });- }-- var fileBinary = httpPostedFile.GetDownloadBits();-- const string qqFileNameParameter = "qqfilename";- var fileName = httpPostedFile.FileName;- if (string.IsNullOrEmpty(fileName) && form.ContainsKey(qqFileNameParameter))- fileName = form[qqFileNameParameter].ToString();- //remove path (passed in IE)- fileName = Path.GetFileName(fileName);-- var contentType = httpPostedFile.ContentType;-- var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();-- if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions))- {- var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.ToLowerInvariant()- .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)- .ToList();- if (!allowedFileExtensions.Contains(fileExtension.ToLowerInvariant()))- {- return Json(new- {- success = false,- message = _translationService.GetResource("ShoppingCart.ValidationFileAllowed"),- downloadGuid = Guid.Empty- });- }- }-- if (attribute.ValidationFileMaximumSize.HasValue)- {- //compare in bytes- var maxFileSizeBytes = attribute.ValidationFileMaximumSize.Value * 1024;- if (fileBinary.Length > maxFileSizeBytes)- {- //when returning JSON the mime-type must be set to text/plain- //otherwise some browsers will pop-up a "Save As" dialog.- return Json(new- {- success = false,- message = string.Format(_translationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), attribute.ValidationFileMaximumSize.Value),- downloadGuid = Guid.Empty- });- }- }-- var download = new Download {- DownloadGuid = Guid.NewGuid(),- UseDownloadUrl = false,- DownloadUrl = "",- DownloadBinary = fileBinary,- ContentType = contentType,- //we store filename without extension for downloads- Filename = Path.GetFileNameWithoutExtension(fileName),- Extension = fileExtension,- IsNew = true- };-- await downloadService.InsertDownload(download);-- //when returning JSON the mime-type must be set to text/plain- //otherwise some browsers will pop-up a "Save As" dialog.- return Json(new- {- success = true,- message = _translationService.GetResource("ShoppingCart.FileUploaded"),- downloadUrl = Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }),- downloadGuid = download.DownloadGuid- });- }-[HttpPost][ClosedStore(true)][PublicStore(true)]diff --git a/src/Web/Grand.Web/Controllers/ContactController.cs b/src/Web/Grand.Web/Controllers/ContactController.csnew file mode 100644index 000000000..69cb4d02a--- /dev/null+++ b/src/Web/Grand.Web/Controllers/ContactController.cs@@ -0,0 +1,237 @@+using Grand.Business.Core.Interfaces.Cms;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Marketing.Contacts;+using Grand.Business.Core.Interfaces.Storage;+using Grand.Domain.Catalog;+using Grand.Domain.Media;+using Grand.Domain.Stores;+using Grand.Infrastructure;+using Grand.Web.Commands.Models.Common;+using Grand.Web.Common.Extensions;+using Grand.Web.Common.Filters;+using Grand.Web.Common.Security.Captcha;+using Grand.Web.Controllers;+using Grand.Web.Events;+using Grand.Web.Models.Common;+using MediatR;+using Microsoft.AspNetCore.Mvc;++public class ContactController: BasePublicController+{+ #region Fields++ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;+ private readonly IMediator _mediator;+ private readonly CaptchaSettings _captchaSettings;++ #endregion++ #region Constructors++ public ContactController(+ ITranslationService translationService,+ IWorkContext workContext,+ IMediator mediator,+ CaptchaSettings captchaSettings)+ {+ _translationService = translationService;+ _workContext = workContext;+ _mediator = mediator;+ _captchaSettings = captchaSettings;+ }++ #endregion++ //available even when a store is closed+ [ClosedStore(true)]+ public virtual async Task<IActionResult> ContactUs(+ [FromServices] StoreInformationSettings storeInformationSettings,+ [FromServices] IPageService pageService)+ {+ if (storeInformationSettings.StoreClosed)+ {+ var closestorepage = await pageService.GetPageBySystemName("ContactUs");+ if (closestorepage is not { AccessibleWhenStoreClosed: true })+ return RedirectToRoute("StoreClosed");+ }++ var model = await _mediator.Send(new ContactUsCommand {+ Customer = _workContext.CurrentCustomer,+ Language = _workContext.WorkingLanguage,+ Store = _workContext.CurrentStore+ });+ return View(model);+ }++ [HttpPost, ActionName("ContactUs")]+ [AutoValidateAntiforgeryToken]+ [ValidateCaptcha]+ [ClosedStore(true)]+ [DenySystemAccount]+ public virtual async Task<IActionResult> ContactUsSend(+ [FromServices] StoreInformationSettings storeInformationSettings,+ [FromServices] IPageService pageService,+ ContactUsModel model, bool captchaValid)+ {+ if (storeInformationSettings.StoreClosed)+ {+ var closestorepage = await pageService.GetPageBySystemName("ContactUs");+ if (closestorepage is not { AccessibleWhenStoreClosed: true })+ return RedirectToRoute("StoreClosed");+ }++ //validate CAPTCHA+ if (_captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage && !captchaValid)+ {+ ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_translationService));+ }++ if (ModelState.IsValid)+ {+ var result = await _mediator.Send(new ContactUsSendCommand {+ CaptchaValid = captchaValid,+ Model = model,+ Store = _workContext.CurrentStore,+ IpAddress = HttpContext?.Connection?.RemoteIpAddress?.ToString()+ });++ if (result.errors.Any())+ {+ foreach (var item in result.errors)+ {+ ModelState.AddModelError("", item);+ }+ }+ else+ {+ //notification+ await _mediator.Publish(new ContactUsEvent(_workContext.CurrentCustomer, result.model));++ model = result.model;+ return View(model);+ }+ }++ var model1 = await _mediator.Send(new ContactUsCommand {+ Customer = _workContext.CurrentCustomer,+ Language = _workContext.WorkingLanguage,+ Store = _workContext.CurrentStore,+ Model = model+ });++ return View(model1);+ }++ [HttpPost]+ [DenySystemAccount]+ public virtual async Task<IActionResult> ContactAttributeChange(ContactAttributeChangeModel model)+ {+ var result = await _mediator.Send(new ContactAttributeChangeCommand {+ Attributes = model.Attributes,+ Customer = _workContext.CurrentCustomer,+ Store = _workContext.CurrentStore+ });+ return Json(new {+ enabledattributeids = result.enabledAttributeIds.ToArray(),+ disabledattributeids = result.disabledAttributeIds.ToArray()+ });+ }++ [HttpPost]+ [DenySystemAccount]+ public virtual async Task<IActionResult> UploadFileContactAttribute(string attributeId,+ [FromServices] IDownloadService downloadService,+ [FromServices] IContactAttributeService contactAttributeService)+ {+ var attribute = await contactAttributeService.GetContactAttributeById(attributeId);+ if (attribute is not { AttributeControlType: AttributeControlType.FileUpload })+ {+ return Json(new {+ success = false,+ downloadGuid = Guid.Empty+ });+ }++ var form = await HttpContext.Request.ReadFormAsync();+ var httpPostedFile = form.Files.FirstOrDefault();+ if (httpPostedFile == null)+ {+ return Json(new {+ success = false,+ message = "No file uploaded",+ downloadGuid = Guid.Empty+ });+ }++ var fileBinary = httpPostedFile.GetDownloadBits();++ const string qqFileNameParameter = "qqfilename";+ var fileName = httpPostedFile.FileName;+ if (string.IsNullOrEmpty(fileName) && form.ContainsKey(qqFileNameParameter))+ fileName = form[qqFileNameParameter].ToString();+ //remove path (passed in IE)+ fileName = Path.GetFileName(fileName);++ var contentType = httpPostedFile.ContentType;++ var fileExtension = Path.GetExtension(fileName);+ if (!string.IsNullOrEmpty(fileExtension))+ fileExtension = fileExtension.ToLowerInvariant();++ if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions))+ {+ var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.ToLowerInvariant()+ .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)+ .ToList();+ if (!allowedFileExtensions.Contains(fileExtension.ToLowerInvariant()))+ {+ return Json(new {+ success = false,+ message = _translationService.GetResource("ShoppingCart.ValidationFileAllowed"),+ downloadGuid = Guid.Empty+ });+ }+ }++ if (attribute.ValidationFileMaximumSize.HasValue)+ {+ //compare in bytes+ var maxFileSizeBytes = attribute.ValidationFileMaximumSize.Value * 1024;+ if (fileBinary.Length > maxFileSizeBytes)+ {+ //when returning JSON the mime-type must be set to text/plain+ //otherwise some browsers will pop-up a "Save As" dialog.+ return Json(new {+ success = false,+ message = string.Format(_translationService.GetResource("ShoppingCart.MaximumUploadedFileSize"),+ attribute.ValidationFileMaximumSize.Value),+ downloadGuid = Guid.Empty+ });+ }+ }++ var download = new Download {+ DownloadGuid = Guid.NewGuid(),+ UseDownloadUrl = false,+ DownloadUrl = "",+ DownloadBinary = fileBinary,+ ContentType = contentType,+ //we store filename without extension for downloads+ Filename = Path.GetFileNameWithoutExtension(fileName),+ Extension = fileExtension,+ IsNew = true+ };++ await downloadService.InsertDownload(download);++ //when returning JSON the mime-type must be set to text/plain+ //otherwise some browsers will pop-up a "Save As" dialog.+ return Json(new {+ success = true,+ message = _translationService.GetResource("ContactUs.FileUploaded"),+ downloadUrl = Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }),+ downloadGuid = download.DownloadGuid+ });+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web/Endpoints/EndpointProvider.cs b/src/Web/Grand.Web/Endpoints/EndpointProvider.csindex 94f750cdd..24886191a 100644--- a/src/Web/Grand.Web/Endpoints/EndpointProvider.cs+++ b/src/Web/Grand.Web/Endpoints/EndpointProvider.cs@@ -326,7 +326,7 @@ namespace Grand.Web.Endpoints//contact usendpointRouteBuilder.MapControllerRoute("ContactUs",pattern + "contactus",- new { controller = "Common", action = "ContactUs" });+ new { controller = "Contact", action = "ContactUs" });//change currencyendpointRouteBuilder.MapControllerRoute("ChangeCurrency",@@ -367,7 +367,7 @@ namespace Grand.Web.Endpoints// contact attributes with "upload file" typeendpointRouteBuilder.MapControllerRoute("UploadFileContactAttribute",pattern + "uploadfilecontactattribute/{attributeId}",- new { controller = "Common", action = "UploadFileContactAttribute" });+ new { controller = "Contact", action = "UploadFileContactAttribute" });//CurrentPosition SaveendpointRouteBuilder.MapControllerRoute("CurrentPosition",diff --git a/src/Web/Grand.Web/Views/Common/ContactUs.cshtml b/src/Web/Grand.Web/Views/Common/ContactUs.cshtmldeleted file mode 100644index 318b4007c..000000000--- a/src/Web/Grand.Web/Views/Common/ContactUs.cshtml+++ /dev/null@@ -1,95 +0,0 @@-@model ContactUsModel-@inject IPageHeadBuilder pagebuilder-@{- Layout = "_SingleColumn";-- //title- pagebuilder.AddTitleParts(Loc["Title.ContactUs"]);-}-<div class="page contact-page">- <h1 class="generalTitle h2">@Loc["Title.ContactUs"]</h1>- <div class="generalMarginSupporter text-left">- @await Component.InvokeAsync("PageBlock", new { systemName = "ContactUs" })- @await Component.InvokeAsync("Widget", new { widgetZone = "contactus_top" })- @if (Model.SuccessfullySent)- {- <div class="alert alert-info">- @Model.Result- </div>- }- else- {- <validation-observer v-slot="{ handleSubmit }">- <form asp-route="ContactUs" method="post" id="contactus-form" ref="form" v-on:submit.prevent="handleSubmit(formSubmit)">- <div asp-validation-summary="ModelOnly" class="message-error"></div>- <div class="form-fields">- <div class="form-group">- <validation-provider tag="div" rules="required" name="FullName" v-slot="{ errors, classes }">- <label asp-for="FullName" class="col-form-label">@Loc["ContactUs.FullName"]:</label>- <span class="required">*</span>- <input asp-for="FullName" v-model="contactus.FullName" placeholder="@Loc["ContactUs.FullName.Hint"]" v-bind:class="[classes , 'form-control']" />- <span class="field-validation-error">{{ errors[0] }}</span>- <span asp-validation-for="FullName"></span>- </validation-provider>- </div>- <div class="form-group">- <validation-provider tag="div" rules="required|email" name="Email" v-slot="{ errors, classes }">- <label asp-for="Email" class="col-form-label">@Loc["ContactUs.Email"]:</label>- <span class="required">*</span>- <input asp-for="Email" v-model="contactus.Email" placeholder="@Loc["ContactUs.Email.Hint"]" v-bind:class="[classes , 'form-control']" />- <span class="field-validation-error">{{ errors[0] }}</span>- <span asp-validation-for="Email"></span>- </validation-provider>- </div>- @if (Model.SubjectEnabled)- {- <div class="form-group">- <validation-provider tag="div" rules="required" name="Subject" v-slot="{ errors, classes }">- <label asp-for="Subject" class="col-form-label">@Loc["ContactUs.Subject"]:</label>- <span class="required">*</span>- <input asp-for="Subject" v-model="contactus.Subject" placeholder="@Loc["ContactUs.Subject.Hint"]" v-bind:class="[classes , 'form-control']" />- <span class="field-validation-error">{{ errors[0] }}</span>- <span asp-validation-for="Subject"></span>- </validation-provider>- </div>- }- <div class="form-group">- <validation-provider tag="div" rules="required" name="Enquiry" v-slot="{ errors, classes }">- <label asp-for="Enquiry" class="col-form-label">@Loc["ContactUs.Enquiry"]:</label>- <span class="required">*</span>- <textarea asp-for="Enquiry" v-model="contactus.Enquiry" placeholder="@Loc["ContactUs.Enquiry.Hint"]" v-bind:class="[classes , 'form-control']" rows="4"></textarea>- <span class="field-validation-error">{{ errors[0] }}</span>- <span asp-validation-for="Enquiry"></span>- </validation-provider>- </div>- </div>- <partial name="Partials/ContactAttributes" model="Model.ContactAttributes" />- @if (Model.DisplayCaptcha)- {- <div class="captcha-box">- <captcha />- </div>- }- <div class="buttons mt-1 mb-1">- <input type="submit" name="send-email" class="btn btn-info contact-us-button" value="@Loc["ContactUs.Button"]" />- </div>- </form>- </validation-observer>- <script asp-location="Footer" asp-order="300">- var contactus = new Vue({- data: () => ({- @{- <text>- FullName: '@Html.Raw(Model.FullName)',- Email: '@Html.Raw(Model.Email)',- Subject: '@Html.Raw(Model.Subject)',- Enquiry: '@Html.Raw(Model.Enquiry)',- </text>- }- })- });- </script>- }- @await Component.InvokeAsync("Widget", new { widgetZone = "contactus_bottom" })- </div>-</div>\ No newline at end of filediff --git a/src/Web/Grand.Web/Views/Common/Partials/ContactAttributes.cshtml b/src/Web/Grand.Web/Views/Common/Partials/ContactAttributes.cshtmldeleted file mode 100644index cd67442cd..000000000--- a/src/Web/Grand.Web/Views/Common/Partials/ContactAttributes.cshtml+++ /dev/null@@ -1,259 +0,0 @@-@using Grand.Business.Core.Interfaces.Storage-@using Grand.Domain.Media-@model IList<ContactUsModel.ContactAttributeModel>-@inject IDownloadService downloadService--@if (Model.Any())-{- var attributeChangeScriptsBuilder = new StringBuilder();- <div class="form-group contact-attributes">- @foreach (var attribute in Model)- {- var controlId = $"contact_attribute_{attribute.Id}";- var controlName = $"attributes[{attribute.Id}]";- var textPrompt = !string.IsNullOrEmpty(attribute.TextPrompt) ? attribute.TextPrompt : attribute.Name;- <div id="@($"contact_attribute_label_{attribute.Id}")" class="col-12 px-0">- <span class="col-form-label text-prompt">- @textPrompt- </span>- @if (attribute.IsRequired)- {- <span class="required">*</span>- }-- @switch (attribute.AttributeControlType)- {- case AttributeControlType.TextBox:- {- <label for="@(controlId)" class="sr-only">"@(controlId)</label>- <input name="@(controlName)" type="text" class="form-control textbox" id="@(controlId)" value="@(attribute.DefaultValue)" />- }- break;- case AttributeControlType.DropdownList:- {- <label for="@(controlId)" class="sr-only">"@(controlId)</label>- <select id="@(controlId)" class="form-control custom-select" name="@(controlName)">- @if (!attribute.IsRequired)- {- <option value="">---</option>- }- @foreach (var attributeValue in attribute.Values)- {- var attributeName = attributeValue.Name;- <option selected="@attributeValue.IsPreSelected" value="@(attributeValue.Id)">@attributeName</option>- }- </select>- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}').addEventListener('change',function(){{contactAttributeChange();}});\n");- }- break;- case AttributeControlType.RadioList:- {- <ul class="option-list pl-0">- @foreach (var attributeValue in attribute.Values)- {- var attributeName = attributeValue.Name;- <li>- <fieldset>- <legend class="sr-only">- @(controlId)- </legend>- <label class="custom-control custom-radio">- <input class="custom-control-input" id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlName)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />- <span class="custom-control-label"></span>- <span class="custom-control-description" for="@(controlId)_@(attributeValue.Id)">@attributeName</span>- </label>-- </fieldset>- </li>- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}_{attributeValue.Id}').addEventListener('click',function(){{contactAttributeChange();}});\n");- }- </ul>- }- break;- case AttributeControlType.Checkboxes:- case AttributeControlType.ReadonlyCheckboxes:- {- <fieldset>- <ul class="option-list pl-0">- @foreach (var attributeValue in attribute.Values.OrderBy(x => x.DisplayOrder))- {- var attributeName = attributeValue.Name;- <li>- <label class="custom-control custom-checkbox">- <input class="custom-control-input" id="@(controlId)_@(attributeValue.Id)" type="checkbox" name="@(controlName)" value="@(attributeValue.Id)" checked="@(attributeValue.IsPreSelected)" @(attribute.AttributeControlType == AttributeControlType.ReadonlyCheckboxes ? Html.Raw(" disabled=\"disabled\"") : null) />- <span class="custom-control-label"></span>- <span class="custom-control-description" for="@(controlId)_@(attributeValue.Id)">@attributeName</span>- </label>- </li>- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}_{attributeValue.Id}').addEventListener('click',function(){{contactAttributeChange();}});\n");- }- </ul>- </fieldset>- }- break;-- case AttributeControlType.MultilineTextbox:- {- <textarea id="@(controlId)" name="@(controlId)">@(attribute.DefaultValue)</textarea>- }- break;- case AttributeControlType.Datepicker:- {- <date-picker-dropdown control-day="@($"attributes[{attribute.Id}_day]")"- control-month="@($"attributes[{attribute.Id}_month]")"- control-year="@($"attributes[{attribute.Id}_year]")"- begin-year="@(DateTime.Now.Year)"- end-year="@(DateTime.Now.Year+1)"- selected-day="attribute.SelectedDay ?? 0"- selected-month="attribute.SelectedMonth ?? 0"- selected-year="attribute.SelectedYear ?? 0"- PartialViewName="Partials/DatePickerDropDowns"- class="input-group" />- }- break;- case AttributeControlType.FileUpload:- {- Download download = null;- if (!string.IsNullOrEmpty(attribute.DefaultValue))- {- download = await downloadService.GetDownloadByGuid(new Guid(attribute.DefaultValue));- }-- //ex. ['jpg', 'jpeg', 'png', 'gif'] or []- var allowedFileExtensions = string.Join(", ", attribute.AllowedFileExtensions.Select(x => "" + x.Trim() + "").ToList());-- if (download != null)- {- <input id="@(controlId)" name="@(controlName)" type="hidden" value="@download.DownloadGuid" />- }- else- {- <input id="@(controlId)" name="@(controlName)" type="hidden" />- }- <template>- <b-form-file accept="@Html.Raw(allowedFileExtensions)" type="file" id="qqfile" name="qqfile" onchange="uploadFile(this)" />- </template>- <input class="hidden-upload-input" type="hidden" onchange="contactAttributeChange()" id="@(controlId)" name="@(controlName)" />- <div id="download-message" class="alert my-2" style="display:none;"></div>- <a id="@(controlId)downloadurl'" class="download-file btn btn-outline-info" style="display:none;">- Download- </a>- <script asp-location="Footer">- function uploadFile(e) {- var formData = new FormData();- formData.append("image", qqfile.files[0]);- axios.post('@(Url.RouteUrl("UploadFileContactAttribute", new {attributeId = attribute.Id}))', formData, {- headers: {- 'Content-Type': 'multipart/form-data'- }- }).then(function (response) {- if (response.data.success) {- var message = response.data.message;- var downloadGuid = response.data.downloadGuid;- var downloadUrl = response.data.downloadUrl;- var downloadBtn = document.querySelector('.download-file');- var messageContainer = document.getElementById('download-message');-- document.querySelector('.hidden-upload-input').setAttribute('value', downloadGuid);- contactAttributeChange();-- messageContainer.style.display = "block";- messageContainer.classList.remove('alert-danger');- messageContainer.classList.add('alert-info');- messageContainer.innerText = message;-- downloadBtn.style.display = "inline-block";- downloadBtn.setAttribute('href', downloadUrl);-- } else {- var message = response.data.message;- var messageContainer = document.getElementById('download-message');- messageContainer.style.display = "block";- messageContainer.classList.remove('alert-info');- messageContainer.classList.add('alert-danger');- messageContainer.innerText = message;- contactAttributeChange();- }- })- }- </script>- }- break;- case AttributeControlType.ColorSquares:- {- <ul class="option-list color-squares w-100 d-inline-flex flex-wrap px-0 mb-0" id="color-squares-@(attribute.Id)">- @foreach (var attributeValue in attribute.Values)- {- var attributeName = attributeValue.Name;- <li class="mr-1 p-0" @(attributeValue.IsPreSelected ? Html.Raw(" class=\"selected-value border border-primary\"") : null)>- <label for="@(controlId)_@(attributeValue.Id)" class="mb-0">- <input id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlName)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />- <span class="color-container" title="@attributeName">- <span class="color" style="background-color:@(attributeValue.ColorSquaresRgb);"> </span>- </span>- </label>- </li>- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}_{attributeValue.Id}').addEventListener('click',function(){{contactAttributeChange();}});\n");- }- </ul>- <script asp-location="Footer">- document.addEventListener("DOMContentLoaded", function () {- var btnContainer = document.querySelector(".contact-attributes #color-squares-@(attribute.Id)");- var btns = btnContainer.getElementsByTagName("li");- for (var i = 0; i < btns.length; i++) {- btns[i].addEventListener("click", function () {- (document.querySelector('.selected-value')) ? document.querySelector('.selected-value').classList.remove('selected-value') : '';- this.classList.add('selected-value');- });- }- });- </script>- }- break;- case AttributeControlType.ImageSquares:- {- //not support attribute type- }- break;- }- </div>- }- </div>-- <script asp-location="Footer">- document.addEventListener("DOMContentLoaded", function () {- contactAttributeChange();- @Html.Raw(attributeChangeScriptsBuilder.ToString())- });- function contactAttributeChange() {- var form = document.querySelector('#contactus-form');- var data = new FormData(form);- axios({- method: 'post',- data: data,- url: '@Html.Raw(Url.Action("contactattributechange", "common"))',- }).then(function (response) {- if (response.data.enabledattributeids) {- for (var i = 0; i < response.data.enabledattributeids.length; i++) {- if (document.querySelector('#contact_attribute_label_' + response.data.enabledattributeids[i])) {- document.querySelector('#contact_attribute_label_' + response.data.enabledattributeids[i]).style.display = 'block';- }- if (document.querySelector('#contact_attribute_input_' + response.data.enabledattributeids[i])) {- document.querySelector('#contact_attribute_input_' + response.data.enabledattributeids[i]).style.display = 'block';- }- }- }- if (response.data.disabledattributeids) {- for (var i = 0; i < response.data.disabledattributeids.length; i++) {- if (document.querySelector('#contact_attribute_label_' + response.data.disabledattributeids[i])) {- document.querySelector('#contact_attribute_label_' + response.data.disabledattributeids[i]).style.display = 'none';- }- if (document.querySelector('#contact_attribute_input_' + response.data.disabledattributeids[i])) {- document.querySelector('#contact_attribute_input_' + response.data.disabledattributeids[i]).style.display = 'none';- }- }- }- })- }- </script>-}\ No newline at end of file