简体   繁体   中英

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

For CREATE function it works perfectly.

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

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

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?

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

now its default value will be null when you select -- Please Select --

Edit

another way is to add a default object manually like

in view

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

and in edit action

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

When using the Tag Helpers in ASP.NET Core the following snippet might help:

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

Note the value="" , without this attribute modelbinding will fail to bind to a nullable int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM