mvc 4错误下拉列表

时间:2013-11-26 01:47:25

标签: asp.net asp.net-mvc-4 drop-down-menu

具有键'WorkStations'的ViewData项的类型为'System.String',但必须是'IEnumerable'类型。

这是我得到的错误,我正在获取dropbox发送的值,但是当它尝试将其添加到数据时它只是崩溃并且我得到了我写下的错误。

这是我的模特

namespace MvCfirstproject.Models
{
    [Table("WorkHoursModels")]
    public class WorkhoursModels
    {
        public int Id { get; set; }
        public string Start { get; set; }
        public string Stop { get; set; }
        public string command { get; set; }
        public string Users { get; set; }
        public string WorkStations { get; set; }


    }
    [Table("WorkStations")]
    public class WorkHoursStation
    {
        public int Id { get; set; }
        public string WorkStations { get; set; }
        public IEnumerable<SelectListItem> Workstations { get; set; }
    }


    public class WorkhourDB : DbContext 
    {
        public DbSet<WorkhoursModels> WorkHours { get; set; }
        public DbSet<WorkHoursStation> WorkStation { get; set; }
    }
}

这是我的控制器

    public ActionResult Create()
    {
        ViewBag.WorkStations = new SelectList(db.WorkStation, "WorkStations", "Workstations");
        return View();
    }

    //
    // POST: /Default1/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(WorkhoursModels workhoursmodels)
    {
        if (workhoursmodels.command == "Users")
        {
            db.WorkHours.Add(workhoursmodels);
            db.SaveChanges();
        }
    }

这是我的观点

 @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <div class="editor-label">
            @Html.LabelFor(model => model.Users)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Users)
            @Html.ValidationMessageFor(model => model.Users)
        </div>

     <div>
       @Html.DropDownList("WorkStations", String.Empty)
    </div>
              <p>
             <input type="submit" name="@Html.NameFor(x => x.command)" value="User"/>

        </p>

 }

2 个答案:

答案 0 :(得分:0)

您需要将下拉列表更新为

   @Html.DropDownList(@ViewBag.Name.WorkStations, String.Empty)

<强>更新

   @Html.DropDownList("WorkStations", (SelectList)ViewBag.WorkStations)

答案 1 :(得分:0)

我有这个工作。不确定它是否是最佳解决方案,但确实有效。

我的Assignment.cs模型(使用Groups.cs模型的组选择列表)

    using System.Web.Mvc;
    //required for SelectListItem

   public virtual Group Group { get; set; }

在我的控制器中

//adds framework for populating dropdown list
using System.Data.Entity.Infrastructure;

在我的视图中

<div class="form-group">
    @Html.LabelFor(model => model.Group.GName, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("GroupID", String.Empty)
        @Html.ValidationMessageFor(model => model.GroupID)
    </div>
</div>