DropDownListFor How to set the default value from a database

So, I have a DropdownListfor that looks like this in my opinion:

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

It works as it should. In my next view, the user should be able to edit his order. So, what I want to do if it opens a form, all my data from it should be displayed, for text fields I got its 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 as with my text fields (giving them the default values ​​from my model) for DropDownListFor when the value is stored in my model (database)? He should like if he chose category 3 earlier and now wants to edit his order earlier, the drop-down list should immediately show category 3.

Thanks for the help!

+4
source share
1 answer

Try this code, it may work in your situation.

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

here you will receive a default edit order from the drop-down menu

   [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 the view with the order you want to edit, and the ProductCategoriesbu popup menu by default contains ProductCategorywhich you want to edit

+3
source

Source: https://habr.com/ru/post/1657251/


All Articles