从ASP.NET MVC中的DropDownList获取默认NULL值 [英] Get a default NULL value from DropDownList in ASP.NET MVC
问题描述
我正在为现有的驱动程序(可以从下拉列表中选择)创建一个预告片.
I am creating a Trailer for existing Driver (that can be selected from Drop Down list).
@Html.DropDownListFor(x => x.Driver.driverID, (SelectList)ViewBag.DriverID, "-- Please Select -- ", new { @class = "form-control" })
对于CREATE函数,它可以完美运行.
For CREATE function it works perfectly.
//Create Get
public ActionResult Create()
{
ViewBag.DriverID = new SelectList(db.Drivers, "driverID", "driverFullName");
return View();
}
对于EDIT功能(编辑预告片编号并保留驱动程序 NULL ),该功能不起作用.
For EDIT function (edit trailers number and leave the driver NULL) it does not work.
//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 驱动程序)?
I have the -- Please Select -- on the drop down list as a first empty value.
How could I put a NULL value on this first empty value (so the trailer would have NO driver selected) from drop down list?
推荐答案
这是因为您在 Drivers
类中的 driverID
属性不是 nullable吗?
因此,当您选择-请选择-
时,它会显示验证消息 driverID字段为必填
,因此您应将 driverID
设置为可空
,例如
this is because your driverID
property in Drivers
class is not nullable ?
that is why when you select -- Please Select --
it gives validation message The driverID field is required
so you should set driverID
to nullable
like
public int? driverID {get;set;}
现在,当您选择时,其默认值为
null
-请选择-
now its default value will be null
when you select -- Please Select --
修改
另一种方法是手动添加默认对象,例如
another way is to add a default object manually like
可见
@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);
}
这篇关于从ASP.NET MVC中的DropDownList获取默认NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!