Get selected item in DropDownList ASP.NET MVC

喜你入骨 提交于 2019-12-18 05:20:31

问题


I know there are multiple threads on how to get the selected value of a DropDownList. However I can't find the right way to get this value from a partial view in my controller.

This is my partial view:

@model List<aptest.Models.answer>

@Html.DropDownList("dropdownlist", new SelectList(Model, "text", "text"))
<button type="submit">next</button>

回答1:


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)



回答2:


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

}


来源:https://stackoverflow.com/questions/22706345/get-selected-item-in-dropdownlist-asp-net-mvc

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