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.

1.2 KB
Raw Blame
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)
    {
        ArgumentNullException.ThrowIfNull(bindingContext);

        if (bindingContext.HttpContext.Request.HasFormContentType)
        {
            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+)\\]", RegexOptions.Compiled, TimeSpan.FromSeconds(1));
        string value = null;
        var match = regex.Match(key);
        if (match.Success) value = match.Groups["Value"].Value;

        return value;
    }
}