Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过IList<;模型>;往返视图getting:ArgumentException:已添加具有相同键的项。关键字:允许_C#_.net_Asp.net Core_Model View Controller - Fatal编程技术网

C# 通过IList<;模型>;往返视图getting:ArgumentException:已添加具有相同键的项。关键字:允许

C# 通过IList<;模型>;往返视图getting:ArgumentException:已添加具有相同键的项。关键字:允许,c#,.net,asp.net-core,model-view-controller,C#,.net,Asp.net Core,Model View Controller,这是我关于StackOverflow的第一个问题,请原谅任何愚蠢的错误。我已经尝试调试这几天了。我是mvc和.netcore2.2框架的新手,但是我已经做了几个小时的一般性研究,特别是针对这个bug的研究,所以非常感谢您的帮助 在我看来,这应该是一个非常简单的修复方法,但事实上,我根本没有使用字典,这让我更加困惑 我正在为用户创建一个用户界面,以便能够以用户友好的方式有效地查询数据库。这涉及到创建IList。每个FilterModel为数据库中的特定属性接收不同的输入 我的过滤器模型: pub

这是我关于StackOverflow的第一个问题,请原谅任何愚蠢的错误。我已经尝试调试这几天了。我是mvc和.netcore2.2框架的新手,但是我已经做了几个小时的一般性研究,特别是针对这个bug的研究,所以非常感谢您的帮助

在我看来,这应该是一个非常简单的修复方法,但事实上,我根本没有使用字典,这让我更加困惑

我正在为用户创建一个用户界面,以便能够以用户友好的方式有效地查询数据库。这涉及到创建IList。每个FilterModel为数据库中的特定属性接收不同的输入

我的过滤器模型:

 public class FilterModel
    {
        public string title { get; set; }
        public string description { get; set; }
        public int? type { get; set; }
        public bool not { get; set; }
        public string input { get; set; }
        public double fromInput { get; set; }
        public double toInput { get; set; }

        //constructor
        public FilterModel(int typeFilter)
        {
            switch (typeFilter)
            {
                case 0:
                    title = "Keywords";
                    type = typeFilter;
                    not = false;
                    description = "This is a keyword filter";
                    //do i need to initiailize input?
                    break;
                case 1:
                    title = "Engagement";
                    type = typeFilter;
                    not = false;
                    fromInput = 1.0;
                    toInput = 20.0;
                    //do i need to initiailize input?
                    break;
                default:
                    break;
            }
        }
    }
控制器中的My Search()函数初始化IList并将其传递给我的搜索视图:

        [HttpGet("/search")]
        public IActionResult Search()
        {
            IList<FilterModel> filters = new List<FilterModel>();


            filters.Add(new FilterModel(0));
            filters.Add(new FilterModel(1));


            return View(filters);

        }
[HttpGet(“/search”)]
公共IActionResult搜索()
{
IList filters=新列表();
filters.Add(新FilterModel(0));
添加(新过滤器模型(1));
返回视图(过滤器);
}
用户可以向IList添加和从中删除IList。此时for循环开始并将每个对象放置在列表中。这是搜索视图:

@model IList<FilterModel>

@using (Html.BeginForm("/searchresultsnew", "Home", FormMethod.Post))
            {
            <ul class="row sort" id="input-filters" style="list-style-type: none">
                @for (int i = 0; i < Model.Count; i++)
                {
                    @await Html.PartialAsync("_FilterEntryEditor", Model[i]);
                }
                <!--<a alt="Add filter" data-target="#myModal" data-toggle="modal" id="MainNavHelp" href="#myModal" class="mx-2 mb-3 input-cols text-center form-group plus alt"></a>-->
            </ul>

                <div class="col-lg-12 text-center">
                    <button type="submit" class="btn btn-success mt-4 mb-4" id="searchButton">Search</button>

                </div>
            }
@model-IList
@使用(Html.BeginForm(“/searchresultsnew”,“Home”,FormMethod.Post))
{
    @for(int i=0;i 搜寻 }
PartialAsync函数使用_FilterEntryEditor文件:

@model FilterModel
@using HtmlHelpers.BeginCollectionItemCore


    <li id="filter-li" class="drag col mx-2 mb-3 input-cols text-center form-group" title="" style="cursor:move ">
        @using (Html.BeginCollectionItem("filters"))
        {
            switch (Model.type)
            {
                //Keyword Filter
                case 0:
                    @Html.DisplayFor(Model => Model.title)
                    @Html.TextArea("Description", null, new
                    {
                        @class = "text-input form-control form-control-alternative mt-1 mb-2",
                        @placeholder = "Wellness, fitness, gym rat, etc.",
                        @rows = "8"
                    })

                    @Html.ValidationMessageFor(Model => Model.input)
                    break;

                case 1:
                    @Html.DisplayFor(Model => Model.title)


                    @Html.EditorFor(Model => Model.fromInput, new { @class = "text-input form-control form-control-alternative mt-1 mb-2" })
                    @Html.EditorFor(Model => Model.toInput, new { @class = "text-input form-control form-control-alternative mt-1 mb-2" })
                    @Html.ValidationMessageFor(Model => Model.fromInput)
                    @Html.ValidationMessageFor(Model => Model.toInput)

                    break;
                default:
                    break;
            }
            <a href="#_" onclick="$(this).parent().remove();">Remove</a>
        }
    </li>
@模型过滤器模型
@使用HtmlHelpers.BeginCollectionItemCore
  • @使用(Html.BeginCollectionItem(“过滤器”)) { 开关(型号) { //关键词过滤器 案例0: @DisplayFor(Model=>Model.title) @TextArea(“Description”),空,新 { @class=“文本输入表单控制表单控制备选方案mt-1 mb-2”, @占位符=“健康、健身、健身鼠等”, @rows=“8” }) @Html.ValidationMessageFor(Model=>Model.input) 打破 案例1: @DisplayFor(Model=>Model.title) @EditorFor(Model=>Model.fromInput,新{@class=“text-input-form-control-form-control-alternative mt-1 mb-2”}) @EditorFor(Model=>Model.toInput,新的{@class=“text-input-form-control-form-control-alternative mt-1 mb-2”}) @Html.ValidationMessageFor(Model=>Model.fromInput) @Html.ValidationMessageFor(Model=>Model.toInput) 打破 违约: 打破 } }
  • 用户完成输入后,表单将发布到控制器中的searchresultsnew函数:

            [HttpPost("/searchresultsnew")]
            [HttpGet("/searchresultsnew")]
            public IActionResult SearchresultsNew(IList<FilterModel> filters)
            {
    
                Debug.WriteLine("Hittt");
                Debug.WriteLine(filters.Count);
                Debug.WriteLine(filters);
                foreach (FilterModel f in filters)
                {
                    Debug.WriteLine(f.title);
                    Debug.WriteLine(f.title);
                    Debug.WriteLine(f.input);
                }
    
                return View();
    
    
            }
    
    [HttpPost(“/searchresultsnew”)]
    [HttpGet(“/searchresultsnew”)]
    公共IActionResult SearchresultsNew(IList筛选器)
    {
    Debug.WriteLine(“Hittt”);
    Debug.WriteLine(filters.Count);
    Debug.WriteLine(过滤器);
    foreach(过滤器中的过滤器模型f)
    {
    Debug.WriteLine(f.title);
    Debug.WriteLine(f.title);
    Debug.WriteLine(f.input);
    }
    返回视图();
    }
    
    这就是我出错的地方。我的所有调试控制台写入都未命中。我在没有BeginCollectionItem的情况下也尝试了这个,但仍然得到相同的错误。我已经删除了大量代码,包括大部分FilterModel。我还创建了一个EditorTemplate来绑定名称,但这也没用

    堆栈跟踪:

    System.ArgumentException: An item with the same key has already been added. Key: Allow
    
       at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
    
       at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
    
       at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.Add(String key, StringValues value)
    
       at Microsoft.AspNetCore.Routing.Matching.HttpMethodMatcherPolicy.<>c__DisplayClass12_0.<CreateRejectionEndpoint>b__0(HttpContext context)
    
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
    
       at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
    
       at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
    
       at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
    
       at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
    
       at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
    
       at Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.<>c__DisplayClass6_0.<<UseStatusCodePagesWithReExecute>b__0>d.MoveNext()
    
    --- End of stack trace from previous location where exception was thrown ---
    
       at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
    
       at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
    
       at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
    
       at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
    
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    
    System.ArgumentException:已添加具有相同密钥的项。关键字:允许
    at System.Collections.Generic.Dictionary`2.TryInsert(TKey键、TValue值、InsertionBehavior)
    at System.Collections.Generic.Dictionary`2.Add(TKey-key,TValue-value)
    在Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.Add(字符串键,字符串值)
    在Microsoft.AspNetCore.Routing.Matching.HttpMethodMatcherPolicy.c__DisplayClass12_0.b__0(HttpContext上下文)中
    位于Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext HttpContext)
    位于Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext HttpContext)
    位于Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext上下文)
    位于Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext上下文)
    在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文)中
    位于Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext上下文)
    在Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.c__DisplayClass6_0.d.MoveNext()中
    ---来自引发异常的上一个位置的堆栈结束跟踪---
    在Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext上下文)中
    位于Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext上下文)
    位于Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext HttpContext)
    位于Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext HttpContext)
    位于Microsoft.AspNetCore.Diag