1

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);
    }
5
  • That's the default behavior, to select the first item. What is the text and value of your null item look like? Commented Aug 2, 2016 at 11:58
  • If the value of property CarrierIDmatches on of your options values, then that option will be selected. And there is no point adding the 4th parameter in the SelectList constructor - its ignored by the DropDownListFor() method which internally builds another IEnumerable<SelectListItem> based on the value of the property. Commented Aug 2, 2016 at 12:01
  • And what is transportOrder? (that does not match your model) Commented Aug 2, 2016 at 12:01
  • 2
    And you can use @Html.DropDownListFor(m => m.CarrierID, (SelectList)ViewBag.CarrierList, "Please select", new { @class = "form-control" }) to generate a null option which will be selected if the value of CarrierID is null or does not match an option. Commented Aug 2, 2016 at 12:04
  • Yeah your right. This do it: @Html.DropDownListFor(model => model.CarrierID, (SelectList)ViewBag.CarrierList, "", htmlAttributes: new { @class = "form-control" }) Commented Aug 2, 2016 at 12:26

1 Answer 1

1

Add "" to DropDownListFor
become like this:

@Html.DropDownListFor(model => model.CarrierID, (SelectList)ViewBag.CarrierList,"", htmlAttributes: new { @class = "form-control" })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.