【问题标题】:ListBoxFor 'List' error needing to be a 'SelectedListItem'ListBoxFor 'List' 错误需要是 'SelectedListItem'
【发布时间】:2017-03-23 19:19:48
【问题描述】:

https://www.codeproject.com/Articles/702890/MVC-Entity-Framework-and-Many-to-Many-Relation 示例之后,我在发布我的 Edit.cshtml 时遇到下一个错误:

“具有“SelectedTelephoneCellulaires”键的 ViewData 项属于“System.Collections.Generic.List”类型,但必须属于“IEnumerable”类型。”

我在网上搜索(当然!),但是两个最接近的相关问题 - 答案(Issues converting types to new selectitemlist && @Html.DropDownListFor not posting back to controller)并没有为我的困难带来任何解决方案。

这是我的 ViewModel 的一部分(为了便于阅读,节食):

public partial class EmployeVM
{        
    public Employe Employe { get; set; } //Employe

    public IEnumerable<SelectListItem> AllTelephoneCellulaires { get; set; } //TelephoneCellulaire        
    private List<int> _selectedTelephoneCellulaires;
    public List<int> SelectedTelephoneCellulaires
    {
        get
        {
            if (_selectedTelephoneCellulaires == null)
            {
                _selectedTelephoneCellulaires = Employe.TelephoneCellulaire1.Select(m => m.IdTelephoneCellulaire).ToList();
            }
            return _selectedTelephoneCellulaires;
        }
        set { _selectedTelephoneCellulaires = value; }
    }
}

}

我的 EmployesController 的某些部分(在节食方面也是如此):

[HttpPost]
    [ValidateAntiForgeryToken]        
    public ActionResult Edit(EmployeVM employeView)
    {
        if (employeView == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        if (ModelState.IsValid)
        {
            var employeToUpdate = db.Employe
                .Include(e => e.TelephoneCellulaire1)
                [...]
                .First(e => e.IdEmploye == employeView.Employe.IdEmploye);

            if (TryUpdateModel(employeToUpdate, "Employe", new string[] { "NomEmploye", "PrenomEmploye", "IdTitre", "IdDepartement", "IdSuperviseur", "DateEmbauche", "DateDepart", "StatutEmploye", "IdEmployeur", "IdLocalisation", "Langue", "CarteAcces", "TelephoneCellulaire", "IdTelephoneBureau", "CarteAffaire", "EquipementInformatique", "AdresseCourriel", "GroupeSecurite", "AccesApplicatif", "CodeAlarme", "CleBatiment", "VehiculeCompagnie", "DateNaissance", "IsSuperviseur", "IsActif" }))
            {
                var newTelephoneCellulaires = db.TelephoneCellulaire.Where(m => employeView.SelectedTelephoneCellulaires.Contains(m.IdTelephoneCellulaire)).ToList();
                [...]

                var updatedTelephoneCellulaires = new HashSet<int>(employeView.SelectedTelephoneCellulaires);
                [...]

                foreach (TelephoneCellulaire telephone in db.TelephoneCellulaire)
                {
                    if (!updatedTelephoneCellulaires.Contains(telephone.IdTelephoneCellulaire))
                    {
                        employeToUpdate.TelephoneCellulaire1.Remove(telephone);
                    }
                    else
                    {
                        employeToUpdate.TelephoneCellulaire1.Add(telephone);
                    }
                }
                [...]

                db.Entry(employeToUpdate).State = EntityState.Modified;
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        if (!ModelState.IsValid)
        {
            foreach (var obj in ModelState.Values)
            {
                foreach (var error in obj.Errors)
                {
                    if (!string.IsNullOrEmpty(error.ErrorMessage))
                        System.Diagnostics.Debug.WriteLine("ERROR WHY = " + error.ErrorMessage);
                }
            }
        }

        return View(employeView);
    }

最后,我的 Edit.cshtml(你猜对了 - 节食...)

<div class="form-group">
        @Html.LabelFor(model => model.AllTelephoneCellulaires, "Téléphones cellulaires", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">               
            @Html.ListBoxFor(m => m.SelectedTelephoneCellulaires, Model.AllTelephoneCellulaires)
        </div>
    </div>

两个先例的答案都解决了“Model.AllTelephoneCellulaires”会导致错误的事实,而不是“m.SelectedTelephoneCellulaires”

最有趣的是,不久前,我能够毫无问题地编辑员工,但当我尝试编辑另一个员工时(都没有触摸“TelephoneCellulaire”输入),砰!错误来了。

我只是不明白为什么会出现此错误?为什么我的 SelectedThing 需要属于“SelectListItem”类型?以及我该如何解决?如果有人有能力帮助我,我将永远感激你。现在,我躲在桌子底下哭泣,像胎儿一样吮吸拇指……

【问题讨论】:

    标签: asp.net-mvc-viewmodel


    【解决方案1】:

    根据您提供的代码,我非常肯定您会收到此错误,因为您没有将有效的 SelectListItem 集合传递给 ListBoxFor 辅助方法。

    我认为 Model.AllTelephoneCellulaires 目前正在返回 NULL,它应该是一个有效的集合。一种解决方案是在 GET 操作方法或视图模型类构造函数中将其初始化为一个空列表。

    public partial class EmployeVM
    {
        // Your other properties goes here.
    
        public IEnumerable<SelectListItem> AllTelephoneCellulaires { get; set; }
        public EmployeVM()
        {
            AllTelephoneCellulaires = new List<SelectListItem>();
        }
    }
    

    【讨论】:

    • 谢谢,它成功了。愿太阳每天都照耀着你在底特律或其他任何地方的生活...... :)
    猜你喜欢
    • 2021-10-26
    • 2022-12-04
    • 2013-06-16
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    相关资源
    最近更新 更多