c# - DropDownListFor 如何从数据库设置默认值

标签 c# html asp.net asp.net-mvc html.dropdownlistfor

所以,我得到了一个在我看来看起来像这样的 DropdownListfor:

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

一切正常。在我的下一个 View 中,用户应该能够编辑他的订单。所以我想做的是,如果他打开表单,应该显示他之前的所有数据,对于文本框,我使用以下代码得到它:

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

所以现在我的问题是,当值存储在我的模型(数据库)中时,我如何才能对 DropDownListFor 执行与文本框相同的操作(从我的模型中为它​​们提供默认值)?如果他之前选择了类别 3,现在想要编辑他之前的订单,那么下拉列表应该会立即显示类别 3。

感谢您的帮助!

最佳答案

尝试此代码可能适合您的情况。

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

在这里您将在下拉列表中获得默认的编辑顺序

   [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();
            }

        }

这将返回包含您要编辑的订单和 ProductCategories 的 View ,下拉菜单默认包含您要编辑的 ProductCategory

关于c# - DropDownListFor 如何从数据库设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39954159/

相关文章:

html - CSS:如何使用 CSS(无 JavaScript、动态宽度和高度、不更改 HTML)在#header 和#content 之间向上移动#thumbnails?

asp.net - 我可以隐藏/显示 asp :Menu items based on role?

c# - CRM 中不同数据类型的计算

javascript - 如何强制运行 swf 文件,而不是下载

jquery - knockout js css 多类绑定(bind)

c# - Request.ServerVariables 抛出 NullReferenceException

c# - 从 TableAdapter 获取@@IDENTITY

c# - 仅从用户点击触发 comboBox SelectedIndexChanged

c# - Windows Phone 8.1 中 ContentDialog 的边框

c# - 将 DataGrid 单元格绑定(bind)到索引属性