RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1374624
Accepted
Boris
Boris
Asked:2022-06-24 19:23:29 +0000 UTC2022-06-24 19:23:29 +0000 UTC 2022-06-24 19:23:29 +0000 UTC

颜色选择器 C# 将颜色传递给控制器

  • 772

大家好。如何将颜色代码传递给控制器​​?我想将颜色存储在数据库中,然后以某种方式使用它,从数据库中获取指定的颜色。存储在字符串中的决定可能不太正确,如果有人告诉我更好的解决方案,我将不胜感激

(function( $ ) {

    $.fn.colorPick = function(config) {

        return this.each(function() {
            new $.colorPick(this, config || {});
        });

    };

    $.colorPick = function (element, options) {
        options = options || {};
        this.options = $.extend({}, $.fn.colorPick.defaults, options);
        if(options.str) {
            this.options.str = $.extend({}, $.fn.colorPick.defaults.str, options.str);
        }
        $.fn.colorPick.defaults = this.options;
        this.color   = this.options.initialColor.toUpperCase();
        this.element = $(element);

        var dataInitialColor = this.element.data('initialcolor');
        if (dataInitialColor) {
            this.color = dataInitialColor;
            this.appendToStorage(this.color);
        }

        var uniquePalette = [];
        $.each($.fn.colorPick.defaults.palette.map(function(x){ return x.toUpperCase() }), function(i, el){
            if($.inArray(el, uniquePalette) === -1) uniquePalette.push(el);
        });

        this.palette = uniquePalette;

        return this.element.hasClass(this.options.pickrclass) ? this : this.init();
    };

    $.fn.colorPick.defaults = {
        'initialColor': '#3498db',
        'paletteLabel': 'Цвета:',
        'allowRecent': true,
        'recentMax': 5,
        'allowCustomColor': false,
        'palette': ["#1abc9c", "#16a085", "#2ecc71", "#27ae60", "#3498db", "#2980b9", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50", "#f1c40f", "#f39c12", "#e67e22", "#d35400", "#e74c3c", "#c0392b", "#ecf0f1", "#bdc3c7", "#95a5a6", "#7f8c8d"],
        'onColorSelected': function() {
            this.element.css({'backgroundColor': this.color, 'color': this.color});
        }
    };

    $.colorPick.prototype = {

        init : function(){

            var self = this;
            var o = this.options;

            $.proxy($.fn.colorPick.defaults.onColorSelected, this)();

            this.element.click(function(event) {
                if (event.target != event.currentTarget){
                    return;
                }

                var offset = $(self.element).offset();

                event.preventDefault();
                self.show(self.element, event.pageX - offset.left, event.pageY - offset.top);

                $('.customColorHash').val(self.color);

                $('.colorPickButton').click(function(event) {
                    self.color = $(event.target).attr('hexValue');
                    self.appendToStorage($(event.target).attr('hexValue'));
                    self.hide();
                    $.proxy(self.options.onColorSelected, self)();
                    return false;
                });
                $('.customColorHash').click(function(event) {
                    return false;
                }).keyup(function (event) {
                    var hash = $(this).val();
                    if (hash.indexOf('#') !== 0) {
                        hash = "#"+hash;
                    }
                    if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hash)) {
                        self.color = hash;
                        self.appendToStorage(hash);
                        $.proxy(self.options.onColorSelected, self)();
                        $(this).removeClass('error');
                    } else {
                        $(this).addClass('error');
                    }
                });

                return false;
            }).blur(function() {
                self.element.val(self.color);
                $.proxy(self.options.onColorSelected, self)();
                self.hide();
                return false;
            });

            $(document).on('click', function(event) {
                if ($.contains(self.element[0], event.target)){
                    return;
                }
                self.hide();
                return true;
            });

            return this;
        },

        appendToStorage: function(color) {
            if ($.fn.colorPick.defaults.allowRecent === true) {
                var storedColors = JSON.parse(localStorage.getItem("colorPickRecentItems"));
                if (storedColors == null) {
                    storedColors = [];
                }
                if ($.inArray(color, storedColors) == -1) {
                    storedColors.unshift(color);
                    storedColors = storedColors.slice(0, $.fn.colorPick.defaults.recentMax)
                    localStorage.setItem("colorPickRecentItems", JSON.stringify(storedColors));
                }
            }
        },

        show: function(element, left, top) {

            $(".colorPickWrapper").remove();

            $(element).prepend('<div class="colorPickWrapper"><div id="colorPick" style="display:none;top:' + top + 'px;left:' + left + 'px"><span>'+$.fn.colorPick.defaults.paletteLabel+'</span></div></div>');

            jQuery.each(this.palette, function (index, item) {
                $("#colorPick").append('<div class="colorPickButton" hexValue="' + item + '" style="background:' + item + '"></div>');
            });
            if ($.fn.colorPick.defaults.allowCustomColor === true) {
                $("#colorPick").append('<input type="text" style="margin-top:5px" class="customColorHash" />');
            }
            if ($.fn.colorPick.defaults.allowRecent === true) {
                $("#colorPick").append('<span style="margin-top:5px">Recent:</span>');
                if (JSON.parse(localStorage.getItem("colorPickRecentItems")) == null || JSON.parse(localStorage.getItem("colorPickRecentItems")) == []) {
                    $("#colorPick").append('<div class="colorPickButton colorPickDummy"></div>');
                } else {
                    jQuery.each(JSON.parse(localStorage.getItem("colorPickRecentItems")), function (index, item) {
                        $("#colorPick").append('<div class="colorPickButton" hexValue="' + item + '" style="background:' + item + '"></div>');
                        if (index == $.fn.colorPick.defaults.recentMax-1) {
                            return false;
                        }
                    });
                }
            }
            $("#colorPick").fadeIn(200);
        },

        hide: function() {
            $( ".colorPickWrapper" ).fadeOut(200, function() {
                $(".colorPickWrapper").remove();
                return this;
            });
        },

    };

}( jQuery ));

创建视图

@using (Html.BeginForm("SaveUploadedFiles", "TrainingType", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div class="container">
        <div class="row">
            <div class="col-sm-6">
                @*ColorPic*@
                @Html.DisplayNameFor(model => model.Picker1)
                <input type="hidden" class="form-control" value="@Model.Id" name="Picker1">
                <div class="picker" id="picker1"></div>
                @*ColorPic*@
            </div>
        </div>       
        <script>
            $("#picker1").colorPick({
                'initialColor': '#8e44ad',
                'palette': ["#1abc9c", "#16a085", "#2ecc71", "#27ae60", "#3498db", "#2980b9", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50", "#f1c40f", "#f39c12", "#e67e22", "#d35400", "#e74c3c", "#c0392b", "#ecf0f1"],
                'onColorSelected': function () {
                    console.log("The user has selected the color: " + this.color);
                    this.element.css({ 'backgroundColor': this.color, 'color': this.color });
                }
            });
        </script>
        <br />
        <div class="row">
            <div class="col-12">
                <button type="submit" class="btn btn-primary">Сохранить</button>
                @Html.ActionLink("Назад", "Index", "", new { @class = "btn btn-primary" })
            </div>
        </div>
    </div>
}

模型

 public class TrainingTypeViewModel : IEntityBase
    {

        [Display(Name = "Цвет")]
        public string Collor { get; set; }

    }

控制器

 [HttpPost]
        [ValidateAntiForgeryToken]
        public override ActionResult Create(TraningViewModel traningModel)
        {
            traningModel.UserId = User.Identity.GetUserId<int>();
            TraningViewModel model = _traningService.getUrl(traningModel);
            if (ModelState.IsValid)
            {
                return base.Create(model);
            }
            return base.Create(traningModel);
        }
javascript
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    Kalmankantaja
    2022-06-24T20:49:16Z2022-06-24T20:49:16Z

    我还没有查看您的 JavaScript 代码中的内容,但我相信您会有所了解。您需要[Bind("названия во View")]在方法中用属性标记参数Create

    模型:

    class Palette
    {
       public string Color { get; set; }
    }
    

    看法:

    <form asp-action="Create">
       <!-- Заметьте, type="color"!!! По аналогии можно сделать так же через hidden, 
            просто через JavaScript задайте свойство value у вашего <input> -->
       <input type="color" asp-for="Color" />
    </form>
    

    控制器:

    class PaletteController : Controller
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Color")] Palette palette)
        {
            if(Model.IsValid)
            {
               //тут ваши действия с palette
            }
            return View(palette);
        }
    }
    
    • 0

相关问题

  • 第二个 Instagram 按钮的 CSS 属性

  • 由于模糊,内容不可见

  • 弹出队列。消息显示不正确

  • 是否可以在 for 循环中插入提示?

  • 如何将 JSON 请求中的信息输出到数据表 Vuetify vue.js?

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5