Reputation: 269
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);
}
Upvotes: 1
Views: 2153
Reputation: 26
Add "" to DropDownListFor
become like this:
@Html.DropDownListFor(model => model.CarrierID, (SelectList)ViewBag.CarrierList,"", htmlAttributes: new { @class = "form-control" })
Upvotes: 1