Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 4 ASP.NET MVC4 DropDownListFor未显示从数据源中选择的值_Asp.net Mvc 4_Razor_Html.dropdownlistfor - Fatal编程技术网

Asp.net mvc 4 ASP.NET MVC4 DropDownListFor未显示从数据源中选择的值

Asp.net mvc 4 ASP.NET MVC4 DropDownListFor未显示从数据源中选择的值,asp.net-mvc-4,razor,html.dropdownlistfor,Asp.net Mvc 4,Razor,Html.dropdownlistfor,在我们的一个ASP.NET MVC 4视图中,我们有一个DropDownList for以及其他html控件,如下所示: @Html.DropDownListFor(model=>model.ProductType, (List<SelectListItem>)ViewBag.ProductType, "--- Select Product Type ----") 该列表是从数据库查找表填

在我们的一个ASP.NET MVC 4视图中,我们有一个DropDownList for以及其他html控件,如下所示:

@Html.DropDownListFor(model=>model.ProductType,
                      (List<SelectListItem>)ViewBag.ProductType,
                      "--- Select Product Type ----")
该列表是从数据库查找表填充的。当我们单击submit按钮时,包括dropdownlist的选定值在内的所有控件值都成功地插入到数据库中。但是,当显示页面时,下拉列表的选定值始终显示为“选择产品类型”,而不是插入到数据库中的值


请帮忙。谢谢。

您需要在控制器内的选择列表中设置所选值,即ViewBag.ProductType

看看SelectList类的重载


我们在控制器ViewBag.ProductType=db.ProductType.Selectx=>new SelectListItem{Text=x.ProductID.ToString,Value=x.ProductType,Selected=true}.ToList;中使用以下内容;。但它仍然不起作用。如果我像你的例子一样使用SelectList,我会得到一个错误,即当前上下文中不存在名称SelectedValue。更新的答案。您正在为所有项目设置Selected=true,这是不正确的。在“var items=…”行和“var selectedItem=…”行中,我得到“对象引用未设置为对象错误的实例”。
public ActionResult MyMethod()
{
    var items = db.ProductType.ToList();
    var selectedItem = items.FirstOrDefault(x => get desired selected item);

    ViewBag.ProductType = 
        new SelectList(items, "ProductID", "ProductType",  selectedItem);
}