这是我得到的错误,我得到了droplist发送的值,但是当它尝试将它添加到数据时它只是崩溃并且我得到了我写的abow错误。
我已尝试将html标记更新为
@ Html.DropDownList(“WorkStations”,(SelectList)ViewBag.WorkStations)
这是我的模特
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>
}
答案 0 :(得分:1)
假设您的视图是针对模型WorkhoursModels
您不需要viewbag,因为您在模型的属性中定义了IEnumerable,只需更改将模型传递给视图的Action
public ActionResult Create()
{
WorkhoursModels model = new WorkhoursModels();
model.Workstations = db.WorkStation.Select(x => new SelectListItem() { Text = x.WorkStations , Value = x.Id.ToString() });
return View(model);
}
使用正确的帮助
@Html.DropDownListFor(model => model.Id, Model.Workstations, string.Empty)