if I edit an element it is possible that the carrierId is null. The controller send the null value. But the view selects the first available value from the dropdownlist and not the null value.
I want that if the value is null no element in die dropdownlist is preselected.
View:
<div class="form-group">
@Html.LabelFor(model => model.CarrierID, "Carrier", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CarrierID, (SelectList)ViewBag.CarrierList, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CarrierID, "", new { @class = "text-danger" })
</div>
</div>
Controller:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Model model= ModelService.Get(id);
if (model== null)
{
return HttpNotFound();
}
ViewBag.CarrierList = new SelectList(db.User, "ID", "Name", model.CarrierID);
return View(model);
}
CarrierIDmatches on of your options values, then that option will be selected. And there is no point adding the 4th parameter in theSelectListconstructor - its ignored by theDropDownListFor()method which internally builds anotherIEnumerable<SelectListItem>based on the value of the property.transportOrder? (that does not match your model)@Html.DropDownListFor(m => m.CarrierID, (SelectList)ViewBag.CarrierList, "Please select", new { @class = "form-control" })to generate anulloption which will be selected if the value ofCarrierIDisnullor does not match an option.@Html.DropDownListFor(model => model.CarrierID, (SelectList)ViewBag.CarrierList, "", htmlAttributes: new { @class = "form-control" })