DropDownList用于检索所选实体

时间:2016-03-17 22:02:34

标签: asp.net-mvc-4

我将值放入编辑框并下拉并按下输入按钮。之后我在后期操作中获得了Rooms实体,但rooms.Locations为空。我检查了ModelState字典,我在那里看到两个键名称和位置以及两个正确的值。但我在Rooms实体中没有看到它。可能有什么不对?

型号:

 namespace SimpleIM.Data
 {
 using System;
 using System.Collections.Generic;
 public partial class Rooms
 {
  public Rooms()
  {
   this.Employees = new HashSet<Employees>();
  }
  public int Id { get; set; }
  public string Name { get; set; }   
  public virtual ICollection<Employees> Employees { get; set; }
  public virtual Locations Locations { get; set; }
 }
}

控制器:

[HttpPost]
public ActionResult Create([Bind(Include = "Id, Name, Locations")] Rooms rooms)
{
 if (ModelState.IsValid)
 {
  db.RoomsSet.Add(rooms);
  db.SaveChanges();
  return RedirectToAction("Index");
 }
 ViewData["Locations"] = new SelectList(db.LocationsSet, "Id", "Name");
 return View();
}

查看:

@using (Html.BeginForm()) 
{
 @Html.AntiForgeryToken()
 <div class="form-horizontal">
 <h4>Rooms</h4>
 <hr />
    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
        </div><br/>
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Locations, (IEnumerable<SelectListItem>) ViewData["Locations"])
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
</div>

0 个答案:

没有答案