ViewBag中的MVC5视图下拉列表

时间:2014-11-04 19:38:54

标签: c# asp.net-mvc dropdownbox

我是MVC5 / C#的新手(刚从Silverlight项目中获得),并且有一个我正在研究的Web应用程序(不是ASP.net)。我无法弄清楚如何从ViewBag填充的下拉列表中获取值,而不是模型。我所看到的一切都是针对ASP.NET和/或填充模型的下拉列表。

我有这种模式换班:

   public class Shift
   {
      public Guid ShiftID { get; set; }
      public string AreaOfOperation { get; set; }
      public string UserName { get; set; }
      public DateTime StartTime { get; set; }
      public DateTime EndTime { get; set; }
   }

这适用于AreaOfOperations:

   public class AreaOfOperations
   {
      public Guid AreaOfOperationsID { get; set; }
      public String AreaOfOperation { get; set; }
      public bool InUse { get; set; }      
   }

相关的控制器代码,通过工作下拉列表很好地填充视图:

  public ActionResult Create(DateTime? datetime)
  {
     List<AreaOfOperations> list = db.AreaOfOperations.Where(i => i.InUse == true).OrderBy(aoo => aoo.AreaOfOperation).ToList();
     ViewBag.DropDownAOOs = new SelectList(list, "AreaOfOperationsID", "AreaOfOperation");

     Shift shift = new Shift();
     shift.ShiftID = Guid.NewGuid();
     shift.StartTime = DateTime.Now;
     shift.UserName = User.Identity.Name;
     return View(shift);
  }

  // POST: Shifts/Create
  // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
  // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
  [HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult Create([Bind(Include = "ShiftID,AreaOfOperations,UserName,StartTime")] Shift shift)
  {
     try
     {
        if (ModelState.IsValid)
        {
           shift.ShiftID = Guid.NewGuid();
           db.Shifts.Add(shift);
           db.SaveChanges();
           return RedirectToAction("Index");
        }
     }
     catch (DataException /* dex */)
     {
        //Log the error (uncomment dex variable name and add a line here to write a log.
        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     return View(shift);
  }

我的观点:

@model CRMgr5.Models.Shift

@{
    ViewBag.Title = "Start Shift";
}

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Shift</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.AreaOfOperations, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("AreaOfOperation", ViewBag.DropDownAOOs as SelectList, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>

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

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

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input id="btnStartShift" type="submit" value="Start Shift" class="btn btn-default" />
            </div>
        </div>
    </div>
}


<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

非常感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:2)

在下拉列表中,您将select命名为“AreaOfOperation”,但model属性称为“AreaOfOperations”。因此,活页夹无法绑定它。

正如此处已有人建议你应该使用强类型的html助手,例如DropDownListFor:

@Html.DropDownListFor(m => m.AreaOfOperations, ViewBag.DropDownAOOs as SelectList)

您为标签做了这个,不确定为什么在生成下拉列表时选择不使用它?

答案 1 :(得分:0)

我只是重新创建了整个事情并且工作正常

我删除了绑定属性

中的AreaOfOperations
[Bind(Include = "ShiftID,AreaOfOperation(s),UserName,StartTime")]

据我所知,您可以完全删除此参数属性。 仅在您只想绑定到视图模型的某些属性时才使用此选项。

但是有一个错误:如果您的ModelState无效,则必须重新填充选择列表。否则你的

  return View(shift);

没有数据来呈现新的SelectList。

另一种方法是将数据放在ViewModel中并在默认构造函数中初始化它。然后你不必担心数据或投射。