具有键&#39;位置&#39;的ViewData项。属于&#39; System.String&#39;但必须属于&#39; IEnumerable <selectlistitem>&#39;

时间:2017-02-17 14:53:48

标签: asp.net-mvc model-view-controller

我从内存数据填充DropDownList并在 POST 上收到此错误。

  

具有键&#39;位置&#39;的ViewData项。属于&#39; System.String&#39;但必须属于&#39; IEnumerable&#39;。

型号:

public class StaffModel
{
    public int id { get; set; }
    public string Email { get; set; }
    [DataType(DataType.Password)]
    public string Password { get; set; }
    [DataType(DataType.Password)]
    public string PasswordConfirm { get; set; }
    public string Emp_Name { get; set; }
    public string Emp_Address { get; set; }
    public string Phone { get; set; }
    public string Position { get; set; }
    public List<SelectListItem> Positions { set; get; }

}

控制器:

public ActionResult Register()
    {

        IEnumerable<SelectListItem> position = db.Positions.Select(p => new SelectListItem
        {
            Text = p.Position_Title,
            Value = p.Position_ID.ToString()
        });
        ViewBag.Position = position;
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(StaffModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                Employee em = new Employee
                {
                    Employee_Name = model.Emp_Name,
                    Address = model.Emp_Address,
                    Phone = model.Phone,
                    Position_ID = Convert.ToInt32(db.Positions.Where(p => p.Position_Title == model.Position).Select(p => p.Position_ID)),
                };
                db.Employees.Add(em);
                db.SaveChanges();
                return RedirectToAction("Index", "Employees");
            }

        }

        return View(model);
    }
enter code here

HTML /剃须刀:

<div class="form-group">
        @Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Position",null, htmlAttributes: new { @class = "form-control" } )
            @Html.ValidationMessageFor(model => model.Position, "", new { @class = "text-danger" })
        </div>
    </div>

2 个答案:

答案 0 :(得分:0)

您在下拉列表中的绑定看起来不正确。

您的模型包含位置,这是您下拉列表的数据。您还有“位置”,我认为这是一个字符串,将被绑定到下拉列表中的选定值。

将您的观点更改为

 @Html.DropDownListFor(x=> x.Position, Model.Positions, new {@class = "form-control"}) )

然后在您的帖子上,通过在用于填充下拉列表的模型的“位置”列表上执行linq查询,看起来好像是在尝试从下拉列表中选择值。您现在应该在模型的“位置”属性中具有所选值。

所以你应该说

Position_ID = model.Position

我还会为您的注册视图使用模型。 有点像...

 public class RegisterViewModel
        {
            public IEnumerable<SelectListItem> Positions { get; set; }
            public string Position { get; set; }
        }

加上您需要的其他字段。

在您的Register操作方法中,填充视图模型并返回视图。

 public ActionResult Register()
        {
            var regModel = new RegisterViewModel
            {
                Positions = db.Positions.Select(p => new SelectListItem
                {
                    Text = p.Position_Title,
                    Value = p.Position_ID.ToString()
                })
            };

            return View("Register",regModel);
        }

您现在不需要使用ViewBag。

希望有所帮助

答案 1 :(得分:0)

它正常工作。谢谢大家帮助我:D

<强>型号:

public class StaffModel
{
    public string Position { get; set; }
    public List<Position> Positions { set; get; }
    public int selectID { get; set; }

}

<强>控制器:

 public ActionResult Register()
    {
        StaffModel st = new StaffModel();
        st.Positions = db.Positions.ToList();
        return View(st);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(StaffModel model)
    {           
        if (ModelState.IsValid)
        {

            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = UserManager.Create(user, model.Password);
            if (result.Succeeded)
            {
                Employee em = new Employee
                {
                    Employee_Name = model.Emp_Name,
                    Address = model.Emp_Address,
                    Phone = model.Phone,
                    Position_ID = model.selectID,
                    ID_User = user.Id
                };
                db.Employees.Add(em);
                db.SaveChanges();

                return RedirectToAction("Index", "Employees");
            }

            else
                AddErrors(result);
        }
        ViewBag.Position = new SelectList(db.Positions, "Position_ID", "Position_Title");
        return View(model);
    }

<强> HTML /剃须刀:

<div class="form-group">
        @Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model=>model.selectID,new SelectList(Model.Positions, "Position_ID", "Position_Title"), htmlAttributes: new { @class = "form-control" } )
            @Html.ValidationMessageFor(model => model.Position, "", new { @class = "text-danger" })
        </div>
    </div>