Get selected item in DropDownList ASP.NET MVC

余生长醉 提交于 2019-11-29 08:41:45

In order to get dropdown value, wrap your select list in a form tag. Use models and DropDownListFor helper

Razor View

@model MyModel

@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
   @Html.DropDownListFor(m => m.Gender, MyModel.GetGenderValues())
   <input type="submit" value="Send" />
}

Controller and other classes

public class MyController : Controller 
{
    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        // Do something

        return View();
    }
}

public class MyModel
{
    public Gender Gender { get; set; }

    public static List<SelectListItem> GetGenderValues()
    {
        return new List<SelectListItem> 
        {
            new SelectListItem { Text = "Male", Value = "Male" };
            new SelectListItem { Text = "Female", Value = "Female" };
        };
    }
}

public enum Gender 
{
    Male, Female
}

And if you use partial view, simply pass your model in it:

@Html.Partial("MyPartialView", Model)
ViewData["list"] = myList.ToList(); 

Razor

@Html.DropDownList("ddl", new SelectList((System.Collections.IEnumerable)ViewData["list"], "Id", "Name"))

Controller

public ActionResult ActionName(String ddl)
{

  // now ddl has your dropdownlist's selected value i.e Id

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!