0

How do I set the value of a SelectList/@Html.DropDownList given the following code?

--Controller:

     public ActionResult Edit(int id)
    {
        Order o = db.Orders.Find(id);

        ViewBag.OrderStatusTId = new SelectList(db.OrderStatusTIds, "OrderStatusTId", "Name", o.OrderStatusTId);  // I thought the last item would send in the selected item to the view?!?!?
        return View(o);
     }          

--View:

@Html.DropDownList("OrderStatusTId", (IEnumerable<SelectListItem>)ViewBag.OrderStatusTId, String.Empty)

1 Answer 1

1

Use viewdata instead of viewbag and change your helper to:

@Html.DropDownList("OrderStatusTId",null, String.Empty)

Sign up to request clarification or add additional context in comments.

2 Comments

Thx! Q1: So why ViewData instead of ViewBag? Q2: How could I set the selected list item from the list itself (Dropdownlist) within the View instead of passing it in from the controller?
DropDownList method automatically looks for a list with the name of the dropdown in the viewdata if you pass null on the items. Yes you could but that would not be recommened since all your logic should remain on your controller.

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.