Skip to content

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.

Contact form - remove IFormCollection

support275053d258cd
diff --git a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs
new file mode 100644
index 000000000..410152624
--- /dev/null
+++ b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs
@@ -0,0 +1,39 @@
+using Grand.Web.Common.Models;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using System.Text.RegularExpressions;
+
+namespace Grand.Web.Common.Binders;
+
+public class CustomAttributesBinder : IModelBinder
+{
+ public Task BindModelAsync(ModelBindingContext bindingContext)
+ {
+ if (bindingContext == null)
+ {
+ throw new ArgumentNullException(nameof(bindingContext));
+ }
+
+ var model = new List<CustomAttributeModel>();
+ var formCollection = bindingContext.HttpContext.Request.Form;
+ foreach (var form in formCollection)
+ {
+ if(form.Key.StartsWith("attributes"))
+ model.Add(new CustomAttributeModel(){ Key = GetKey(form.Key), Value = form.Value} );
+ }
+
+ bindingContext.Result = ModelBindingResult.Success(model);
+ return Task.CompletedTask;
+ }
+
+ private static string GetKey(string key)
+ {
+ var regex = new Regex("\\[(?<Value>\\w+)\\]");
+ string value = null;
+ Match match = regex.Match(key);
+ if(match.Success)
+ {
+ value = match.Groups["Value"].Value;
+ }
+ return value;
+ }
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs
new file mode 100644
index 000000000..1101b7d77
--- /dev/null
+++ b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs
@@ -0,0 +1,23 @@
+using Grand.Web.Common.Models;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
+
+namespace Grand.Web.Common.Binders;
+
+public class CustomAttributesBinderProvider : IModelBinderProvider
+{
+ public IModelBinder GetBinder(ModelBinderProviderContext context)
+ {
+ if (context == null)
+ {
+ throw new ArgumentNullException(nameof(context));
+ }
+
+ if (context.Metadata.ModelType == typeof(IList<CustomAttributeModel>))
+ {
+ return new BinderTypeModelBinder(typeof(CustomAttributesBinder));
+ }
+
+ return null;
+ }
+}
diff --git a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
index b99db003e..d9f6952f6 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
@@ -12,7 +12,6 @@ using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Plugins;
using Grand.Infrastructure.TypeSearch;
-using Grand.Infrastructure.Validators;
using Grand.SharedKernel.Extensions;
using Grand.Web.Common.Themes;
using Microsoft.AspNetCore.Builder;
@@ -32,7 +31,6 @@ using WebMarkupMin.AspNet.Common.Compressors;
using WebMarkupMin.AspNet.Common.UrlMatchers;
using WebMarkupMin.AspNetCore6;
using WebMarkupMin.NUglify;
-
using IWmmLogger = WebMarkupMin.Core.Loggers.ILogger;
using WmmThrowExceptionLogger = WebMarkupMin.Core.Loggers.ThrowExceptionLogger;
@@ -59,8 +57,9 @@ namespace Grand.Web.Common.Infrastructure
if (DataSettingsManager.DatabaseIsInstalled())
{
//whether to allow the use of anti-forgery cookies from SSL protected page on the other store pages which are not
- options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
-
+ options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways
+ ? CookieSecurePolicy.Always
+ : CookieSecurePolicy.SameAsRequest;
}
});
}
@@ -80,7 +79,9 @@ namespace Grand.Web.Common.Infrastructure
};
if (DataSettingsManager.DatabaseIsInstalled())
{
- options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
+ options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways
+ ? CookieSecurePolicy.Always
+ : CookieSecurePolicy.SameAsRequest;
}
});
}
@@ -122,22 +123,25 @@ namespace Grand.Web.Common.Infrastructure
if (azureConfig.PersistKeysToAzureKeyVault)
services.AddDataProtection()
// This blob must already exist before the application is run
- .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString, azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName)
+ .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString,
+ azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName)
.ProtectKeysWithAzureKeyVault(new Uri(azureConfig.KeyIdentifier),
- new DefaultAzureCredential());
+ new DefaultAzureCredential());
else
{
services.AddDataProtection()
- .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString, azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName);
+ .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString,
+ azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName);
}
-
}
else
{
var securityConfig = new SecurityConfig();
configuration.GetSection("Security").Bind(securityConfig);
- var dataProtectionKeysPath = string.IsNullOrEmpty(securityConfig.KeyPersistenceLocation) ? CommonPath.DataProtectionKeysPath : securityConfig.KeyPersistenceLocation;
+ var dataProtectionKeysPath = string.IsNullOrEmpty(securityConfig.KeyPersistenceLocation)
+ ? CommonPath.DataProtectionKeysPath
+ : securityConfig.KeyPersistenceLocation;
var dataProtectionKeysFolder = new DirectoryInfo(dataProtectionKeysPath);
//configure the data protection system to persist keys to the specified directory
@@ -165,22 +169,28 @@ namespace Grand.Web.Common.Infrastructure
//add main cookie authentication
authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.AuthenticationScheme, options =>
{
- options.Cookie.Name = securityConfig.CookiePrefix + GrandCookieAuthenticationDefaults.AuthenticationScheme;
+ options.Cookie.Name =
+ securityConfig.CookiePrefix + GrandCookieAuthenticationDefaults.AuthenticationScheme;
options.Cookie.HttpOnly = true;
options.LoginPath = GrandCookieAuthenticationDefaults.LoginPath;
options.AccessDeniedPath = GrandCookieAuthenticationDefaults.AccessDeniedPath;
- options.Cookie.SecurePolicy = securityConfig.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
+ options.Cookie.SecurePolicy = securityConfig.CookieSecurePolicyAlways
+ ? CookieSecurePolicy.Always
+ : CookieSecurePolicy.SameAsRequest;
});
//add external authentication
authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme, options =>
{
- options.Cookie.Name = securityConfig.CookiePrefix + GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;
+ options.Cookie.Name = securityConfig.CookiePrefix +
+ GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;
options.Cookie.HttpOnly = true;
options.LoginPath = GrandCookieAuthenticationDefaults.LoginPath;
options.AccessDeniedPath = GrandCookieAuthenticationDefaults.AccessDeniedPath;
- options.Cookie.SecurePolicy = securityConfig.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
+ options.Cookie.SecurePolicy = securityConfig.CookieSecurePolicyAlways
+ ? CookieSecurePolicy.Always
+ : CookieSecurePolicy.SameAsRequest;
});
//register external authentication plugins now
@@ -194,7 +204,6 @@ namespace Grand.Web.Common.Infrastructure
//add new Authentication
foreach (var instance in externalAuthInstances)
instance.AddAuthentication(authenticationBuilder, configuration);
-
}
/// <summary>
@@ -214,7 +223,7 @@ namespace Grand.Web.Common.Infrastructure
var securityConfig = new SecurityConfig();
configuration.GetSection("Security").Bind(securityConfig);
- if(securityConfig.EnableRuntimeCompilation) mvcBuilder.AddRazorRuntimeCompilation();
+ if (securityConfig.EnableRuntimeCompilation) mvcBuilder.AddRazorRuntimeCompilation();
if (securityConfig.UseHsts)
{
@@ -250,7 +259,8 @@ namespace Grand.Web.Common.Infrastructure
services.AddValidatorsFromAssemblies(assemblies);
//MVC now serializes JSON with camel case names by default, use this code to avoid it
- mvcBuilder.AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
+ mvcBuilder.AddNewtonsoftJson(options =>
+ options.SerializerSettings.ContractResolver = new DefaultContractResolver());
//register controllers as services, it'll allow to override them
mvcBuilder.AddControllersAsServices();
@@ -277,8 +287,10 @@ namespace Grand.Web.Common.Infrastructure
options.IgnoredPaths.Add("/.well-known/pki-validation");
//determine who can access the MiniProfiler results
options.ResultsAuthorize = request =>
- !request.HttpContext.RequestServices.GetRequiredService<PerformanceConfig>().DisplayMiniProfilerInPublicStore ||
- request.HttpContext.RequestServices.GetRequiredService<IPermissionService>().Authorize(StandardPermission.AccessAdminPanel).Result;
+ !request.HttpContext.RequestServices.GetRequiredService<PerformanceConfig>()
+ .DisplayMiniProfilerInPublicStore ||
+ request.HttpContext.RequestServices.GetRequiredService<IPermissionService>()
+ .Authorize(StandardPermission.AccessAdminPanel).Result;
});
}
@@ -302,16 +314,15 @@ namespace Grand.Web.Common.Infrastructure
});
}
}
-
+
public static void AddGrandHealthChecks(this IServiceCollection services)
{
var connection = DataSettingsManager.LoadSettings();
var hcBuilder = services.AddHealthChecks();
hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy());
hcBuilder.AddMongoDb(connection.ConnectionString,
- name: "mongodb-check",
- tags: new[] { "mongodb" });
-
+ name: "mongodb-check",
+ tags: new[] { "mongodb" });
}
public static void AddHtmlMinification(this IServiceCollection services, IConfiguration configuration)
@@ -322,55 +333,53 @@ namespace Grand.Web.Common.Infrastructure
{
// Add WebMarkupMin services
services.AddWebMarkupMin(options =>
- {
- options.AllowMinificationInDevelopmentEnvironment = true;
- options.AllowCompressionInDevelopmentEnvironment = true;
- })
- .AddHtmlMinification(options =>
- {
- options.MinificationSettings.RemoveOptionalEndTags = false;
-
- options.ExcludedPages = new List<IUrlMatcher> {
- new WildcardUrlMatcher("/swagger/*"),
- new WildcardUrlMatcher("/admin/*"),
- new ExactUrlMatcher("/admin")
- };
- options.CssMinifierFactory = new NUglifyCssMinifierFactory();
- options.JsMinifierFactory = new NUglifyJsMinifierFactory();
- })
- .AddXmlMinification(options =>
- {
- options.ExcludedPages = new List<IUrlMatcher> {
- new WildcardUrlMatcher("/swagger/*"),
- new WildcardUrlMatcher("/admin/*"),
- new ExactUrlMatcher("/admin")
- };
- })
- .AddHttpCompression(options =>
- {
- options.ExcludedPages = new List<IUrlMatcher> {
- new WildcardUrlMatcher("/swagger/*")
- };
- options.CompressorFactories = new List<ICompressorFactory>
- {
- new BuiltInBrotliCompressorFactory(new BuiltInBrotliCompressionSettings
- {
- Level = CompressionLevel.Fastest
- }),
- new DeflateCompressorFactory(new DeflateCompressionSettings
- {
- Level = CompressionLevel.Fastest
- }),
- new GZipCompressorFactory(new GZipCompressionSettings
- {
- Level = CompressionLevel.Fastest
- })
+ {
+ options.AllowMinificationInDevelopmentEnvironment = true;
+ options.AllowCompressionInDevelopmentEnvironment = true;
+ })
+ .AddHtmlMinification(options =>
+ {
+ options.MinificationSettings.RemoveOptionalEndTags = false;
+
+ options.ExcludedPages = new List<IUrlMatcher> {
+ new WildcardUrlMatcher("/swagger/*"),
+ new WildcardUrlMatcher("/admin/*"),
+ new ExactUrlMatcher("/admin")
};
- });
+ options.CssMinifierFactory = new NUglifyCssMinifierFactory();
+ options.JsMinifierFactory = new NUglifyJsMinifierFactory();
+ })
+ .AddXmlMinification(options =>
+ {
+ options.ExcludedPages = new List<IUrlMatcher> {
+ new WildcardUrlMatcher("/swagger/*"),
+ new WildcardUrlMatcher("/admin/*"),
+ new ExactUrlMatcher("/admin")
+ };
+ })
+ .AddHttpCompression(options =>
+ {
+ options.ExcludedPages = new List<IUrlMatcher> {
+ new WildcardUrlMatcher("/swagger/*")
+ };
+ options.CompressorFactories = new List<ICompressorFactory> {
+ new BuiltInBrotliCompressorFactory(new BuiltInBrotliCompressionSettings {
+ Level = CompressionLevel.Fastest
+ }),
+ new DeflateCompressorFactory(new DeflateCompressionSettings {
+ Level = CompressionLevel.Fastest
+ }),
+ new GZipCompressorFactory(new GZipCompressionSettings {
+ Level = CompressionLevel.Fastest
+ })
+ };
+ });
}
+
if (performanceConfig.HtmlMinificationErrors)
services.AddSingleton<IWmmLogger, WmmThrowExceptionLogger>();
}
+
public static void AddApplicationInsights(this IServiceCollection services, IConfiguration configuration)
{
var applicationInsights = new ApplicationInsightsConfig();
@@ -379,8 +388,8 @@ namespace Grand.Web.Common.Infrastructure
{
services.AddApplicationInsightsTelemetry();
}
-
}
+
/// <summary>
/// Adds services for WebEncoderOptions
/// </summary>
@@ -397,7 +406,6 @@ namespace Grand.Web.Common.Infrastructure
}
-
/// <summary>
/// Adds services for detection device
/// </summary>
diff --git a/src/Web/Grand.Web.Common/Models/CustomAttributeModel.cs b/src/Web/Grand.Web.Common/Models/CustomAttributeModel.cs
new file mode 100644
index 000000000..7b796dcfa
--- /dev/null
+++ b/src/Web/Grand.Web.Common/Models/CustomAttributeModel.cs
@@ -0,0 +1,7 @@
+namespace Grand.Web.Common.Models;
+
+public class CustomAttributeModel
+{
+ public string Key { get; set; }
+ public string Value { get; set; }
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Commands/Handler/Common/ContactAttributeChangeCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Common/ContactAttributeChangeCommandHandler.cs
index 0861083d8..3c6300a86 100644
--- a/src/Web/Grand.Web/Commands/Handler/Common/ContactAttributeChangeCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Common/ContactAttributeChangeCommandHandler.cs
@@ -7,13 +7,15 @@ using MediatR;
namespace Grand.Web.Commands.Handler.Common
{
- public class ContactAttributeChangeCommandHandler : IRequestHandler<ContactAttributeChangeCommand, (IList<string> enabledAttributeIds, IList<string> disabledAttributeIds)>
+ public class ContactAttributeChangeCommandHandler : IRequestHandler<ContactAttributeChangeCommand, (IList<string>
+ enabledAttributeIds, IList<string> disabledAttributeIds)>
{
private readonly IContactAttributeService _contactAttributeService;
private readonly IContactAttributeParser _contactAttributeParser;
private readonly IDownloadService _downloadService;
- public ContactAttributeChangeCommandHandler(IContactAttributeService contactAttributeService, IContactAttributeParser contactAttributeParser,
+ public ContactAttributeChangeCommandHandler(IContactAttributeService contactAttributeService,
+ IContactAttributeParser contactAttributeParser,
IDownloadService downloadService)
{
_contactAttributeService = contactAttributeService;
@@ -21,7 +23,8 @@ namespace Grand.Web.Commands.Handler.Common
_downloadService = downloadService;
}
- public async Task<(IList<string> enabledAttributeIds, IList<string> disabledAttributeIds)> Handle(ContactAttributeChangeCommand request, CancellationToken cancellationToken)
+ public async Task<(IList<string> enabledAttributeIds, IList<string> disabledAttributeIds)> Handle(
+ ContactAttributeChangeCommand request, CancellationToken cancellationToken)
{
var customAttributes = await ParseContactAttributes(request);
@@ -39,6 +42,7 @@ namespace Grand.Web.Commands.Handler.Common
disabledAttributeIds.Add(attribute.Id);
}
}
+
return (enabledAttributeIds, disabledAttributeIds);
}
@@ -48,105 +52,108 @@ namespace Grand.Web.Commands.Handler.Common
var contactAttributes = await _contactAttributeService.GetAllContactAttributes(request.Store.Id);
foreach (var attribute in contactAttributes)
{
- string controlId = string.Format("contact_attribute_{0}", attribute.Id);
switch (attribute.AttributeControlType)
{
case AttributeControlType.DropdownList:
case AttributeControlType.RadioList:
case AttributeControlType.ColorSquares:
case AttributeControlType.ImageSquares:
+ {
+ var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
+ if (!string.IsNullOrEmpty(ctrlAttributes))
{
- request.Form.TryGetValue(controlId, out var ctrlAttributes);
- if (!string.IsNullOrEmpty(ctrlAttributes))
- {
- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
- attribute, ctrlAttributes).ToList();
-
- }
+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
+ attribute, ctrlAttributes).ToList();
}
+ }
break;
case AttributeControlType.Checkboxes:
+ {
+ var cblAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
+ if (!string.IsNullOrEmpty(cblAttributes))
{
- request.Form.TryGetValue(controlId, out var cblAttributes);
- if (!string.IsNullOrEmpty(cblAttributes))
+ foreach (var item in cblAttributes.Split(','))
{
- foreach (var item in cblAttributes)
- {
- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes, attribute, item).ToList();
- }
+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes, attribute, item).ToList();
}
}
+ }
break;
case AttributeControlType.ReadonlyCheckboxes:
+ {
+ //load read-only (already server-side selected) values
+ var attributeValues = attribute.ContactAttributeValues;
+ foreach (var selectedAttributeId in attributeValues
+ .Where(v => v.IsPreSelected)
+ .Select(v => v.Id)
+ .ToList())
{
- //load read-only (already server-side selected) values
- var attributeValues = attribute.ContactAttributeValues;
- foreach (var selectedAttributeId in attributeValues
- .Where(v => v.IsPreSelected)
- .Select(v => v.Id)
- .ToList())
- {
- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
- attribute, selectedAttributeId.ToString()).ToList();
- }
+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
+ attribute, selectedAttributeId.ToString()).ToList();
}
+ }
break;
case AttributeControlType.TextBox:
case AttributeControlType.MultilineTextbox:
+ {
+ var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
+ if (!string.IsNullOrEmpty(ctrlAttributes))
{
- request.Form.TryGetValue(controlId, out var ctrlAttributes);
- if (!string.IsNullOrEmpty(ctrlAttributes))
- {
- string enteredText = ctrlAttributes.ToString().Trim();
- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
- attribute, enteredText).ToList();
- }
+ var enteredText = ctrlAttributes.Trim();
+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
+ attribute, enteredText).ToList();
}
+ }
break;
case AttributeControlType.Datepicker:
+ {
+ var date = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_day")?.Value;
+ var month = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_month")?.Value;
+ var year = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_year")?.Value;
+ DateTime? selectedDate = null;
+ try
{
- request.Form.TryGetValue(controlId + "_day", out var date);
- request.Form.TryGetValue(controlId + "_month", out var month);
- request.Form.TryGetValue(controlId + "_year", out var year);
- DateTime? selectedDate = null;
- try
- {
- selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(date));
- }
- catch { }
- if (selectedDate.HasValue)
- {
- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
- attribute, selectedDate.Value.ToString("D")).ToList();
- }
+ selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(date));
+ }
+ catch
+ {
+ // ignored
+ }
+
+ if (selectedDate.HasValue)
+ {
+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
+ attribute, selectedDate.Value.ToString("D")).ToList();
}
+ }
break;
case AttributeControlType.FileUpload:
+ {
+ var guid = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
+ Guid.TryParse(guid, out var downloadGuid);
+ var download = await _downloadService.GetDownloadByGuid(downloadGuid);
+ if (download != null)
{
- Guid downloadGuid;
- request.Form.TryGetValue(controlId, out var guid);
- Guid.TryParse(guid, out downloadGuid);
- var download = await _downloadService.GetDownloadByGuid(downloadGuid);
- if (download != null)
- {
- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
- attribute, download.DownloadGuid.ToString()).ToList();
- }
+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
+ attribute, download.DownloadGuid.ToString()).ToList();
}
+ }
break;
default:
break;
}
}
+
//validate conditional attributes (if specified)
foreach (var attribute in contactAttributes)
{
var conditionMet = await _contactAttributeParser.IsConditionMet(attribute, customAttributes);
if (conditionMet.HasValue && !conditionMet.Value)
- customAttributes = _contactAttributeParser.RemoveContactAttribute(customAttributes, attribute).ToList();
+ customAttributes = _contactAttributeParser.RemoveContactAttribute(customAttributes, attribute)
+ .ToList();
}
return customAttributes;
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Commands/Handler/Common/ContactUsCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Common/ContactUsCommandHandler.cs
index dd42f3446..cb71cca93 100644
--- a/src/Web/Grand.Web/Commands/Handler/Common/ContactUsCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Common/ContactUsCommandHandler.cs
@@ -53,19 +53,20 @@ namespace Grand.Web.Commands.Handler.Common
TextPrompt = attribute.GetTranslation(x => x.TextPrompt, request.Language.Id),
IsRequired = attribute.IsRequired,
AttributeControlType = attribute.AttributeControlType,
- DefaultValue = request.Form?[$"contact_attribute_{attribute.Id}"] ?? attribute.DefaultValue,
+ DefaultValue = request.Model?.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value ?? attribute.DefaultValue
};
if (attribute.AttributeControlType == Domain.Catalog.AttributeControlType.Datepicker)
{
- int.TryParse(request.Form?[$"contact_attribute_{attribute.Id}_day"], out var selectedDay);
+ int.TryParse(request.Model?.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_day")?.Value, out var selectedDay);
+ int.TryParse(request.Model?.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_month")?.Value,out var selectedMonth);
+ int.TryParse(request.Model?.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_year")?.Value, out var selectedYear);
+
if (selectedDay > 0)
attributeModel.SelectedDay = selectedDay;
- int.TryParse(request.Form?[$"contact_attribute_{attribute.Id}_month"], out var selectedMonth);
if (selectedMonth > 0)
attributeModel.SelectedMonth = selectedMonth;
- int.TryParse(request.Form?[$"contact_attribute_{attribute.Id}_year"], out var selectedYear);
if (selectedYear > 0)
attributeModel.SelectedYear = selectedYear;
}
@@ -83,7 +84,8 @@ namespace Grand.Web.Commands.Handler.Common
var attributeValues = attribute.ContactAttributeValues;
foreach (var attributeValue in attributeValues)
{
- var preSelected = request.Form?[$"contact_attribute_{attribute.Id}"].ToString();
+ var preSelected = request.Model?.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
+
var attributeValueModel = new ContactUsModel.ContactAttributeValueModel {
Id = attributeValue.Id,
Name = attributeValue.GetTranslation(x => x.Name, request.Language.Id),
diff --git a/src/Web/Grand.Web/Commands/Handler/Common/ContactUsSendCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Common/ContactUsSendCommandHandler.cs
index 63f0146d5..eb35ca3ad 100644
--- a/src/Web/Grand.Web/Commands/Handler/Common/ContactUsSendCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Common/ContactUsSendCommandHandler.cs
@@ -88,7 +88,6 @@ namespace Grand.Web.Commands.Handler.Common
var contactAttributes = await _contactAttributeService.GetAllContactAttributes(request.Store.Id);
foreach (var attribute in contactAttributes)
{
- string controlId = string.Format("contact_attribute_{0}", attribute.Id);
switch (attribute.AttributeControlType)
{
case AttributeControlType.DropdownList:
@@ -96,7 +95,7 @@ namespace Grand.Web.Commands.Handler.Common
case AttributeControlType.ColorSquares:
case AttributeControlType.ImageSquares:
{
- request.Form.TryGetValue(controlId, out var ctrlAttributes);
+ var ctrlAttributes = request.Model.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
if (!string.IsNullOrEmpty(ctrlAttributes))
{
customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,
@@ -107,10 +106,11 @@ namespace Grand.Web.Commands.Handler.Common
break;
case AttributeControlType.Checkboxes:
{
- request.Form.TryGetValue(controlId, out var cblAttributes);
+ var cblAttributes = request.Model.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
+
if (!string.IsNullOrEmpty(cblAttributes))
{
- foreach (var item in cblAttributes)
+ foreach (var item in cblAttributes.Split(','))
{
customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes, attribute, item).ToList();
}
@@ -134,7 +134,7 @@ namespace Grand.Web.Commands.Handler.Common
case AttributeControlType.TextBox:
case AttributeControlType.MultilineTextbox:
{
- request.Form.TryGetValue(controlId, out var ctrlAttributes);
+ var ctrlAttributes = request.Model.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
if (!string.IsNullOrEmpty(ctrlAttributes))
{
var enteredText = ctrlAttributes.ToString().Trim();
@@ -145,9 +145,9 @@ namespace Grand.Web.Commands.Handler.Common
break;
case AttributeControlType.Datepicker:
{
- request.Form.TryGetValue(controlId + "_day", out var date);
- request.Form.TryGetValue(controlId + "_month", out var month);
- request.Form.TryGetValue(controlId + "_year", out var year);
+ var date = request.Model.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_day")?.Value;
+ var month = request.Model.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_month")?.Value;
+ var year = request.Model.Attributes.FirstOrDefault(x => x.Key == attribute.Id+ "_year")?.Value;
DateTime? selectedDate = null;
try
{
@@ -163,7 +163,7 @@ namespace Grand.Web.Commands.Handler.Common
break;
case AttributeControlType.FileUpload:
{
- request.Form.TryGetValue(controlId, out var guid);
+ var guid = request.Model.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
Guid.TryParse(guid, out Guid downloadGuid);
var download = await _downloadService.GetDownloadByGuid(downloadGuid);
if (download != null)
diff --git a/src/Web/Grand.Web/Commands/Models/Common/ContactAttributeChangeCommand.cs b/src/Web/Grand.Web/Commands/Models/Common/ContactAttributeChangeCommand.cs
index c962ec9cf..aa77d985b 100644
--- a/src/Web/Grand.Web/Commands/Models/Common/ContactAttributeChangeCommand.cs
+++ b/src/Web/Grand.Web/Commands/Models/Common/ContactAttributeChangeCommand.cs
@@ -1,13 +1,13 @@
using Grand.Domain.Customers;
using Grand.Domain.Stores;
+using Grand.Web.Common.Models;
using MediatR;
-using Microsoft.AspNetCore.Http;
namespace Grand.Web.Commands.Models.Common
{
public class ContactAttributeChangeCommand : IRequest<(IList<string> enabledAttributeIds, IList<string> disabledAttributeIds)>
{
- public IFormCollection Form { get; set; }
+ public IList<CustomAttributeModel> Attributes { get; set; }
public Customer Customer { get; set; }
public Store Store { get; set; }
diff --git a/src/Web/Grand.Web/Commands/Models/Common/ContactUsCommand.cs b/src/Web/Grand.Web/Commands/Models/Common/ContactUsCommand.cs
index b6d8ee045..deb504d81 100644
--- a/src/Web/Grand.Web/Commands/Models/Common/ContactUsCommand.cs
+++ b/src/Web/Grand.Web/Commands/Models/Common/ContactUsCommand.cs
@@ -3,7 +3,6 @@ using Grand.Domain.Localization;
using Grand.Domain.Stores;
using Grand.Web.Models.Common;
using MediatR;
-using Microsoft.AspNetCore.Http;
namespace Grand.Web.Commands.Models.Common
{
@@ -13,6 +12,5 @@ namespace Grand.Web.Commands.Models.Common
public Store Store { get; set; }
public Language Language { get; set; }
public ContactUsModel Model { get; set; }
- public IFormCollection Form { get; set; }
}
}
diff --git a/src/Web/Grand.Web/Commands/Models/Common/ContactUsSendCommand.cs b/src/Web/Grand.Web/Commands/Models/Common/ContactUsSendCommand.cs
index 95bb90b4f..1d80930e6 100644
--- a/src/Web/Grand.Web/Commands/Models/Common/ContactUsSendCommand.cs
+++ b/src/Web/Grand.Web/Commands/Models/Common/ContactUsSendCommand.cs
@@ -1,4 +1,5 @@
using Grand.Domain.Stores;
+using Grand.Web.Common.Models;
using Grand.Web.Models.Common;
using MediatR;
using Microsoft.AspNetCore.Http;
@@ -8,7 +9,6 @@ namespace Grand.Web.Commands.Models.Common
public class ContactUsSendCommand : IRequest<(ContactUsModel model, IList<string> errors)>
{
public ContactUsModel Model { get; set; }
- public IFormCollection Form { get; set; }
public bool CaptchaValid { get; set; }
public string IpAddress { get; set; }
public Store Store { get; set; }
diff --git a/src/Web/Grand.Web/Controllers/CommonController.cs b/src/Web/Grand.Web/Controllers/CommonController.cs
index 5e6833f84..dfafe0d8e 100644
--- a/src/Web/Grand.Web/Controllers/CommonController.cs
+++ b/src/Web/Grand.Web/Controllers/CommonController.cs
@@ -355,7 +355,7 @@ namespace Grand.Web.Controllers
public virtual async Task<IActionResult> ContactUsSend(
[FromServices] StoreInformationSettings storeInformationSettings,
[FromServices] IPageService pageService,
- ContactUsModel model, IFormCollection form, bool captchaValid)
+ ContactUsModel model, bool captchaValid)
{
if (storeInformationSettings.StoreClosed)
{
@@ -374,7 +374,6 @@ namespace Grand.Web.Controllers
{
var result = await _mediator.Send(new ContactUsSendCommand() {
CaptchaValid = captchaValid,
- Form = form,
Model = model,
Store = _workContext.CurrentStore,
IpAddress = HttpContext?.Connection?.RemoteIpAddress?.ToString()
@@ -390,21 +389,20 @@ namespace Grand.Web.Controllers
else
{
//notification
- await _mediator.Publish(new ContactUsEvent(_workContext.CurrentCustomer, result.model, form));
+ await _mediator.Publish(new ContactUsEvent(_workContext.CurrentCustomer, result.model));
model = result.model;
return View(model);
}
}
- model = await _mediator.Send(new ContactUsCommand() {
+ var model1 = await _mediator.Send(new ContactUsCommand() {
Customer = _workContext.CurrentCustomer,
Language = _workContext.WorkingLanguage,
Store = _workContext.CurrentStore,
Model = model,
- Form = form
});
- return View(model);
+ return View(model1);
}
@@ -528,10 +526,10 @@ namespace Grand.Web.Controllers
[HttpPost]
[DenySystemAccount]
- public virtual async Task<IActionResult> ContactAttributeChange(IFormCollection form)
+ public virtual async Task<IActionResult> ContactAttributeChange(ContactAttributeChangeModel model)
{
var result = await _mediator.Send(new ContactAttributeChangeCommand() {
- Form = form,
+ Attributes = model.Attributes,
Customer = _workContext.CurrentCustomer,
Store = _workContext.CurrentStore
});
diff --git a/src/Web/Grand.Web/Events/ContactUsEvent.cs b/src/Web/Grand.Web/Events/ContactUsEvent.cs
index 9e0ad6613..964717b59 100644
--- a/src/Web/Grand.Web/Events/ContactUsEvent.cs
+++ b/src/Web/Grand.Web/Events/ContactUsEvent.cs
@@ -11,11 +11,10 @@ namespace Grand.Web.Events
public ContactUsModel Model { get; private set; }
public IFormCollection Form { get; private set; }
- public ContactUsEvent(Customer customer, ContactUsModel model, IFormCollection form)
+ public ContactUsEvent(Customer customer, ContactUsModel model)
{
Customer = customer;
Model = model;
- Form = form;
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Models/Common/ContactAttributeChangeModel.cs b/src/Web/Grand.Web/Models/Common/ContactAttributeChangeModel.cs
new file mode 100644
index 000000000..535421e7f
--- /dev/null
+++ b/src/Web/Grand.Web/Models/Common/ContactAttributeChangeModel.cs
@@ -0,0 +1,14 @@
+using Grand.Web.Common.Binders;
+using Grand.Web.Common.Models;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Grand.Web.Models.Common;
+public class ContactAttributeChangeModel
+{
+ public ContactAttributeChangeModel()
+ {
+ Attributes = new List<CustomAttributeModel>();
+ }
+ [ModelBinder(BinderType = typeof(CustomAttributesBinder))]
+ public IList<CustomAttributeModel> Attributes { get; set; }
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Models/Common/ContactUsModel.cs b/src/Web/Grand.Web/Models/Common/ContactUsModel.cs
index 95ff2348c..d195ab161 100644
--- a/src/Web/Grand.Web/Models/Common/ContactUsModel.cs
+++ b/src/Web/Grand.Web/Models/Common/ContactUsModel.cs
@@ -2,6 +2,9 @@
using Grand.Infrastructure.ModelBinding;
using Grand.Infrastructure.Models;
using Grand.Domain.Common;
+using Grand.Web.Common.Binders;
+using Grand.Web.Common.Models;
+using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Models.Common
{
@@ -11,6 +14,7 @@ namespace Grand.Web.Models.Common
{
ContactAttributes = new List<ContactAttributeModel>();
ContactAttribute = new List<CustomAttribute>();
+ Attributes = new List<CustomAttributeModel>();
}
[GrandResourceDisplayName("ContactUs.Email")]
@@ -31,6 +35,9 @@ namespace Grand.Web.Models.Common
public bool DisplayCaptcha { get; set; }
+ [ModelBinder(BinderType = typeof(CustomAttributesBinder))]
+ public IList<CustomAttributeModel> Attributes { get; set; }
+
public string ContactAttributeInfo { get; set; }
public IList<CustomAttribute> ContactAttribute { get; set; }
public IList<ContactAttributeModel> ContactAttributes { get; set; }
diff --git a/src/Web/Grand.Web/Views/Common/Partials/ContactAttributes.cshtml b/src/Web/Grand.Web/Views/Common/Partials/ContactAttributes.cshtml
index 7d8067586..a7ab2372b 100644
--- a/src/Web/Grand.Web/Views/Common/Partials/ContactAttributes.cshtml
+++ b/src/Web/Grand.Web/Views/Common/Partials/ContactAttributes.cshtml
@@ -9,9 +9,10 @@
<div class="form-group contact-attributes">
@foreach (var attribute in Model)
{
- string controlId = string.Format("contact_attribute_{0}", attribute.Id);
- string textPrompt = !string.IsNullOrEmpty(attribute.TextPrompt) ? attribute.TextPrompt : attribute.Name;
- <div id="@string.Format("contact_attribute_label_{0}", attribute.Id)" class="col-12 px-0">
+ 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>
@@ -25,13 +26,13 @@
case AttributeControlType.TextBox:
{
<label for="@(controlId)" class="sr-only">"@(controlId)</label>
- <input name="@(controlId)" type="text" class="form-control textbox" id="@(controlId)" value="@(attribute.DefaultValue)" />
+ <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="@(controlId)">
+ <select id="@(controlId)" class="form-control custom-select" name="@(controlName)">
@if (!attribute.IsRequired)
{
<option value="">---</option>
@@ -57,7 +58,7 @@
@(controlId)
</legend>
<label class="custom-control custom-radio">
- <input class="custom-control-input" id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />
+ <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>
@@ -79,7 +80,7 @@
var attributeName = attributeValue.Name;
<li>
<label class="custom-control custom-checkbox">
- <input class="custom-control-input" id="@(controlId)_@(attributeValue.Id)" type="checkbox" name="@(controlId)" value="@(attributeValue.Id)" checked="@(attributeValue.IsPreSelected)" @(attribute.AttributeControlType == AttributeControlType.ReadonlyCheckboxes ? Html.Raw(" disabled=\"disabled\"") : null) />
+ <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>
@@ -98,9 +99,9 @@
break;
case AttributeControlType.Datepicker:
{
- <date-picker-dropdown control-day="@(controlId + "_day")"
- control-month="@(controlId + "_month")"
- control-year="@(controlId + "_year")"
+ <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.HasValue ? attribute.SelectedDay.Value : 0)"
@@ -123,16 +124,16 @@
if (download != null)
{
- <input id="@(controlId)" name="@(controlId)" type="hidden" value="@download.DownloadGuid" />
+ <input id="@(controlId)" name="@(controlName)" type="hidden" value="@download.DownloadGuid" />
}
else
{
- <input id="@(controlId)" name="@(controlId)" type="hidden" />
+ <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="@(controlId)" />
+ <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
@@ -186,7 +187,7 @@
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="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />
+ <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);">&nbsp;</span>
</span>