【问题标题】:How to limit the number tags an author can insert如何限制作者可以插入的标签数量
【发布时间】:2017-10-30 19:13:06
【问题描述】:

我目前正在使用 asp.net 核心构建博客。我知道我可以使用数据注释来限制标题中使用的字符串的长度。如何限制用户输入的标签数量?比如这里最多只能输入5个标签,在stackoverflow上。

  public class Post
        {
            public int PostId { get; set; }

            [MaximumLength(50)] 
            public string Title { get; set; }

            public ICollection<PostTag> PostTags { get; set; }
        }


   public class PostTag
       {
         public int TagId { get; set; }
         public Tag Tag { get; set; }

         public int PostId { get; set; }
         public Post Post { get; set;}
         }



    public class Tag
    {
        public int TagId { get; set; }
        public string Text { get; set; }

        public ICollection<PostTag> PostTags { get; set }

【问题讨论】:

  • 你必须编写代码才能做到这一点,没有内置任何东西。
  • 添加类似 Enumerable.TakeWhile 方法怎么样 (IEnumerable, Func)
  • 您可以编写一个自定义验证器,用于提示查看here。如果您搜索一下,您还可以找到许多现有的问题。

标签: c# data-annotations


【解决方案1】:

简单地说,您需要编写限制它的代码。执行此操作的方法很大程度上取决于您希望如何填充它。

这是一个简单的例子来说明我将如何做到这一点

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public class Posts
        {
            public Posts()
            {
                _tags = new List<string>();
            }

            private List<string> _tags { get;}

            public List<string> Tags
            {
                get { return _tags ; }
            }

            public bool AddTag(string tag)
            {
                var maxTag = 5; // put in config

                if (_tags.Count() + 1 > maxTag)
                {
                    //throw new Exception("unable to add tag... too many tags");
                    return false;
                }

                _tags.Add(tag);
                return true;
            }
        }

        public static void Main()
        {
            // limit tags to 5

            var post = new Posts();

            for (var a = 0; a < 10; a++)
            {
                Console.WriteLine(post.AddTag(a.ToString())
                    ? "Added " + a + " to the tags"
                    : "Failed to add " + a + " to the tags");
            }


        }
    }
}

基本上我在模型中有一个 tags 属性,但它只能通过类中的方法访问。这将防止规避 add/get 方法。

main 的结果如下所示。

Added 0 to the tags
Added 1 to the tags
Added 2 to the tags
Added 3 to the tags
Added 4 to the tags
Failed to add 5 to the tags
Failed to add 6 to the tags
Failed to add 7 to the tags
Failed to add 8 to the tags
Failed to add 9 to the tags

如果这有帮助,请告诉我

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2021-05-02
    • 2014-02-18
    • 1970-01-01
    • 2021-05-02
    相关资源
    最近更新 更多