asp.net mvc 如何在编辑模式下从 dropdownlistfor 中获取选定的项目

How to get selected item from dropdownlistfor in edit mode in asp.net mvc

我似乎在页面加载之前尝试编辑下拉菜单时遇到错误。这是错误: 'System.InvalidOperationException' 类型的异常发生在 System.Web.Mvc.dll 中,但未在用户代码中处理

附加信息:具有键 'Manager' 的 ViewData 项是 'System.String' 类型,但必须是 'IEnumerable'.

类型

我想做的就是从 dropdownlistfor 中获取选定的列表项。我希望它像创建接受时一样填充,让我在创建中选择的选定项目出现在编辑中。这是我的代码:

型号:

namespace NewHireApp1.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.ComponentModel;

public partial class NewHire
{
    public int ID { get; set; }
    [DisplayName("Manager Email")]
    public string Manager { get; set; }
    public string Managers_Email { get; set; }
    public string HR_Emp { get; set; }
    public string Emp_FirstName { get; set; }
    public string Emp_LastName { get; set; }
    public Nullable<System.DateTime> Emp_StartDate { get; set; }
    public string Emp_OfficeLocation { get; set; }
    public string Emp_Department { get; set; }
    public string Emp_Title { get; set; }

    public SelectList ADList { get; set; }
}
}

控制器:

    [HttpGet]
    public ActionResult NewHire(NewHire objadmodel)
    {
        /*Getting data from database*/
        List<ActiveDirectory> objadlist = (from data in objentity.ActiveDirectories select data).ToList();
        objadmodel.ADList = objadlist.Select(m => new SelectListItem { Value = m.mail, Text = m.mail });
        return View(objadmodel);
    }

    public ActionResult NewHireEdit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        NewHire newhire = _entities.NewHires.Find(id);
        List<ActiveDirectory> objadlist = (from data in objentity.ActiveDirectories select data).ToList();
        newhire.ADList = objadlist.Select(m => new SelectListItem { Value = m.mail, Text = m.mail });
        ViewBag.ADList = objadlist.Select(m => new SelectListItem { Value = m.mail, Text = m.mail });
        if (newhire == null)
        {
            return HttpNotFound();
        }
        return View(newhire);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult NewHireEdit(NewHire newhire, int? id)
    {


        if (ModelState.IsValid)
        {
            _entities.Entry(newhire).State = EntityState.Modified;
            _entities.SaveChanges();
            return RedirectToAction("NewHireDetails", this.RouteData.Values);
        }
        return View(newhire);
    }

查看:

  <div class="form-group">
        @Html.LabelFor(model => model.Manager, "Hiring Manager Email:", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.Manager, Model.ADList, String.Empty, htmlAttributes: new { @id = "ddlAD", @style = "width:500px;", @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Manager, "", new { @class = "text-danger" })
        </div>
    </div>

我可能做错了什么导致我无法检索到所选项目?我是 MVC 的新手,所以这让我很疯狂,我一辈子都弄不明白。提前感谢您的任何反馈。

不要自己创建 SelectList。如果这样做,您有责任 select 使用正确的项目。相反,只需使用 IEnumerable<SelectListItem>:

public IEnumerable<SelectListItem> ADList { get; set; }

那么,在你的行动中:

objadmodel.ADList = objadlist.Select(m => new SelectListItem { Value = m.mail, Text = m.mail });

此外,您还需要在编辑操作中填充此 属性。实际上,您根本不应该将此 属性 存储在您的实体上。使用视图模型或将 select 列表项放入 ViewBag:

ViewBag.ADList = objadlist.Select(m => new SelectListItem { Value = m.mail, Text = m.mail });

然后:

@Html.DropDownListFor(m => m.Manager, (IEnumerable<SelectListItem>)ViewBag.ADList)

视图模型是更好的方法。一般来说,您应该尽可能避免使用 ViewBag,不过,这种狭窄的实例是少数可以接受的用途之一。