Selected value for dropdownlistfor in mvc4

前端 未结 1 1341
臣服心动
臣服心动 2020-12-10 09:20

I have created a ViewBag selectlist in Edit action and set the value to be selected as:

ViewBag.Doors = new SelectList(
    new[]
    {
        new {ID = 1,          


        
1条回答
  •  时光说笑
    2020-12-10 09:58

    How will I do it using Annonymous type in ViewBag ?

    Overload

    enter image description here

    Controller Action Method

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

    View

    @Html.DropDownList("Doors")
    






    How will I do it using SelectListItem?

    Action Method

    [HttpGet]
    public ActionResult DropDownListFor()
    {
        List items = new List();
    
        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();
    }
    

    View

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






    How will I do it using View Model?

    View

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

    Action Method

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

    View Model

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

    0 讨论(0)
提交回复
热议问题