DropDown in .Net MVC3

前端 未结 3 2019
盖世英雄少女心
盖世英雄少女心 2021-01-28 03:08

I am trying to create a dropdonw in my MVC web application.

Model

namespace projectname.Models 
{
public class DropDownModel
    {
         public int i         


        
3条回答
  •  春和景丽
    2021-01-28 04:10

    There are a few ways of display DropDownList in MVC. Here is my way.

    Note: You need a collection of SelectListItem in model.

    Model

    public class MyModel
    {
        public int SelectedId { get; set; }
        public IList AllItems { get; set; }
    
        public MyModel()
        {
            AllItems = new List();
        }
    }
    

    Controller

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new MyModel();
            model.AllItems = new List
            {
                new SelectListItem { Text = "One",  Value = "1"},
                new SelectListItem { Text = "Two",  Value = "2"},
                new SelectListItem { Text = "Three",  Value = "3"}
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(MyModel model)
        {
            // Get the selected value
            int id = model.SelectedId;
            return View();
        }
    }
    

    View

    @model DemoMvc.Controllers.MyModel
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.DropDownListFor(x => x.SelectedId, Model.AllItems)
        
    }
    

    enter image description here

提交回复
热议问题