ViewBag中的MVC5视图下拉列表

本文关键字:下拉列表 视图 MVC5 中的 ViewBag | 更新日期: 2023-09-27 18:29:18

我是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; }
   }

这是针对作战区域:

   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")
}

如有任何帮助,我们将不胜感激。谢谢

ViewBag中的MVC5视图下拉列表

在下拉列表中,您将您的选择命名为"AreaOfOperation",但模型属性称为"AreaOfOperations"。因此绑定器将无法绑定它。

正如这里有人已经建议你应该使用强类型的html助手,如DropDownListFor:

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

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

我刚刚重新创建了整个东西,它运行得很好

我在你的绑定属性中删除了AreaOfOperations的s

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

据我所知,你可以一起删除这个参数属性。只有当您只想绑定到视图模型的某些属性时,才会使用此选项。

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

  return View(shift);

没有用于呈现新SelectList的数据。

另一种方法是将数据放在ViewModel中,并在默认构造函数中初始化它。那么你就不必担心数据或选角了。