提交失败验证后未重新填充多个选择类别字段

时间:2019-06-11 13:59:45

标签: c# validation razor model-view-controller multi-select

我有一个多选下拉菜单选项,您可以根据需要选择任意多个值。表单和验证似乎按预期方式工作,但是我注意到,如果“选择”了多个选择选项(例如选择了5个),并且验证后表单失败,则多重选择仅在验证后返回1个选择的选项。似乎验证无论如何都只能返回1值。表单验证失败后,如何获取返回所有选定值的表单? (说所有5个都选中)

我尝试添加特殊的逻辑,该逻辑将类别数组传递给MultiSelect重载。从理论上讲,这应该起作用,但似乎并不能在视图中反映这些值?验证提交失败后,获取所有多选值以返回的最佳方法是什么。

我添加了一些屏幕截图,以帮助更好地理解我的Controller和View代码。

提交之前 Before Submission

提交后(请注意缺少报告类别字段) After Submission

控制器

  private void getReportCategoryList(int[] categoryIds){

            //New Multi Select List. Gets all category combinations 
            var categories = db.Report_Category_NEW.Select(c => new
            {
                CategoryID = c.ReportCategoryID,
                CategoryName = c.ReportCategory
            }).OrderBy(c => c.CategoryName).ToList();

            //Place Categories in ViewData for View()
            if(categoryIds == null)
            {
            //If categoryIds is null, no categoryIds to pre populate
                ViewData["Categories"] = new MultiSelectList(categories, "CategoryID", "CategoryName");
            }
            else
            {
            //If categoryIds is NOT null, pre populate the MultiSelectList using the categoryIds array
                ViewData["Categories"] = new MultiSelectList(categories, "CategoryID", "CategoryName", categoryIds);
            }
        }

查看

                  <div class="form-group">
                        @Html.LabelFor(model => model.Report_Category, "Report Category", htmlAttributes: new { @class = "control-label col-md-2 required" })
                        <div class="col-md-5">
                            @Html.DropDownList("CategoryIds", (MultiSelectList)ViewData["Categories"], new { multiple = "multiple", @class = "select2 form-control" })
                            @Html.ValidationMessageFor(model => model.CategoryIds, "", new { @class = "badge badge-default badge-danger text-left" })
                        </div>
                    </div>

0 个答案:

没有答案