RawMVC
RawMVC

Reputation: 123

DropDownListFor How to set a default value from a database

So, I got a DropdownListfor that looks like that in my view:

@Html.DropDownListFor(m => m.ProductCategory, new SelectList(Model.ProductCategories.OrderBy(m => m.PCNumber), "", "Name"), "")

That works like it should. In my next view the user should be able to edit his order. So what I want to do is, if he opens the form all of his data from before should be displayed, for textboxes I got it work with the following code:

 @Html.TextBoxFor(m => m.NameOfProduct, new { @Value = @Model.NameofProduct })

So now my problem is how can I do the same thing that I did with my textboxes (giving them default values from my model) for a DropDownListFor when the value is stored in my model(database)? It should like that if he selected Category 3 before and now wants to edit his order from before, the dropdownlist should show category 3 right away.

Thank you for any help!

Upvotes: 4

Views: 1698

Answers (1)

Ankush Guhe
Ankush Guhe

Reputation: 797

Try this code may be it work in your situation.

@Html.DropDownListFor(m=> m.PCNumber, new SelectList(m.ProductCategories, "PCNumber", "ProductCategory"), "-- Select Category --", new { @class = "form-control" })

here you will get default edit order in your dropdown

   [HttpGet]
        public ActionResult EditOrder(int? id)
        {
            _obj_order_detail = db.order_detail.Find(id);
            if (_obj_order_detail != null)
            {
                _obj_order_detail.ProductCategories = db.category_detail.ToList(); //get category List
                return View(_obj_order_detail);
            }
            else
            {
                return view();
            }

        }

this will return view with order which you want to edit and ProductCategories and dropdown bu default contain ProductCategory which you want to edit

Upvotes: 3

Related Questions