mvc4中dropdownlistfor的选定值

时间:2013-08-29 09:28:27

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我在“编辑”操作中创建了一个ViewBag选择列表,并将值设置为:

ViewBag.Doors = new SelectList(
    new[]
    {
        new {ID = 1, Name="1-Door"},
        new {ID = 2, Name="2-Doors"},
        new {ID = 3, Name="3-Doors"},
        new {ID = 4, Name="4-Doors"},
        new {ID = 5, Name="5-Doors"},
        new {ID = 6, Name="6-Doors"},
        new {ID = 7, Name="7-Doors"}
    },
    "ID", "Name", advert.Doors);

但在视图中,默认情况下未选中下拉列表的值。

我的观看代码是:

@Html.DropDownListFor(model => model.Doors, (SelectList)ViewBag.Doors, "--Select--")
@Html.ValidationMessageFor(model => model.Doors)

属性门将是数字1,2,3,..

1 个答案:

答案 0 :(得分:12)

如何在ViewBag中使用Annonymous类型?

<强>过载

enter image description here

控制器操作方法

public ActionResult DropDownListFor()
{
    ViewBag.Doors = new SelectList(
                        new[]
                        {
                            new {Value = 1,Text="1-Door"},
                            new {Value = 2,Text="2-Door"},
                            new {Value = 3,Text="4-Door"},
                            new {Value = 4,Text="4-Door"},
                            new {Value = 5,Text="5-Door"},
                            new {Value = 6,Text="6-Door"},
                            new {Value = 7,Text="7-Doors"}
                        }, "Value", "Text", 7);
    return View();
}

查看

@Html.DropDownList("Doors")






我将如何使用SelectListItem?

行动方法

[HttpGet]
public ActionResult DropDownListFor()
{
    List<SelectListItem> items = new List<SelectListItem>();

    items.Add(new SelectListItem { Text = "Action", Value = "0" });
    items.Add(new SelectListItem { Text = "Drama", Value = "1" });
    items.Add(new SelectListItem { Text = "Comedy", Value = "2", 
                                                             Selected = true });
    items.Add(new SelectListItem { Text = "Science Fiction", Value = "3" });
    ViewBag.MovieType = items;

    return View();
}

查看

@using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
    @Html.DropDownList("MovieType")
}






我将如何使用View Model?

查看

@using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
    @Html.DropDownListFor(m => m.Id, Model.DDLList, "Please select");
}

行动方法

[HttpGet]
public ActionResult DropDownListFor()
{
    return View(new Models.Dropdown());
}

查看模型

public class Dropdown
{
    public string Id { get; set; }
    public List<SelectListItem> DDLList
    {
        get
        {
            return new List<SelectListItem>() 
            { 
                new SelectListItem
                { 
                    Text = "1-Door", 
                    Value = "1", 
                    Selected = true
                },
                new SelectListItem
                { 
                    Selected = false, 
                    Value = "2", 
                    Text = "2-Door"
                }
            };
        }
    }
}