【问题标题】:Get a default NULL value from DropDownList in ASP.NET MVC从 ASP.NET MVC 中的 DropDownList 获取默认的 NULL 值
【发布时间】:2017-07-26 17:11:32
【问题描述】:

我正在为现有 Driver(可以从下拉列表中选择)创建一个 Trailer

@Html.DropDownListFor(x => x.Driver.driverID, (SelectList)ViewBag.DriverID, "-- Please Select -- ", new { @class = "form-control" })

对于 CREATE 功能,它可以完美运行。

//Create Get
public ActionResult Create()
{
    ViewBag.DriverID = new SelectList(db.Drivers, "driverID", "driverFullName");
    return View();
}

对于 EDIT 功能(编辑预告片编号并保留驱动程序 NULL)它不起作用。

//Edit Get
public ActionResult Edit(int? id)
{
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     Trailer trailer = db.Trailers.Find(id);
     if (trailer == null)
     {
         return HttpNotFound();
     }
     ViewBag.DriverID = new SelectList(db.Drivers.ToList(), "driverID", "driverFullName");
     return View(trailer);
}    

我有-- 请在下拉列表中选择-- 作为第一个空值
我怎样才能从下拉列表中将 NULL 值放在第一个空值上(因此预告片将选择 NO 驱动程序)?

【问题讨论】:

  • 请向我们展示在您的控制器中创建和编辑操作以及如何填充 ViewBag.DriverID。
  • 为什么要null
  • 如果 --Please Select-- 被选中,这意味着它的 NULL 对吗?为什么你想要 null?
  • --请选择-- 只是一个空槽。我想为拖车选择一个 NULL,没有选择驱动程序。
  • 您能提供 Drivers 模型并且您想选择 -- 请选择 -- 将返回 null 吗?但是当它--请选择--时你不能提交对吗?

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

这是因为您在 Drivers 类中的 driverID 属性不是 nullable ? 这就是为什么当您选择 -- Please Select -- 时它会给出验证消息 The driverID field is required 所以您应该将 driverID 设置为 nullable like

public int? driverID {get;set;}

现在,当您选择 -- Please Select -- 时,其默认值为 null

编辑

另一种方法是手动添加默认对象

在视图中

 @Html.DropDownListFor(x => x.Driver.driverID, (SelectList)ViewBag.DriverID, new { @class = "form-control" })

在编辑操作中

public ActionResult Edit(int? id)
{
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     Trailer trailer = db.Trailers.Find(id);
     if (trailer == null)
     {
         return HttpNotFound();
     }

     var list = db.Drivers.ToList();
     list.Insert(0, new Drivers() {driverFullName = "-- Please Select --"});
     ViewBag.DriverID = new SelectList(list, "driverID", "driverFullName"); //showing the list of drivers on edit page
     return View(trailer);
}

【讨论】:

  • 这是我的拖车模型类。我有它int? public class Trailer { public int trailerID { get; set; } public int? DriverID { get; set; } public virtual Driver Driver { get; set; } }
  • 一开始就是这样。我从以前就有了。它没有帮助
  • 你在代码中使用 Driver.driverID 所以它应该在驱动类中
  • 但是Driver类中的driverID是主键
  • 您使用的是视图模型还是域模型?
【解决方案2】:

在 ASP.NET Core 中使用 Tag Helpers 时,以下 sn-p 可能会有所帮助:

<select asp-for="DriverId" asp-items="DriverIdList" class="form-control">
  <option value="">-- please select --</option>
</select>

注意value="",没有这个属性modelbinding将无法绑定到一个可为空的int。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 2019-06-05
    • 1970-01-01
    • 2013-10-19
    相关资源
    最近更新 更多