【问题标题】:Get selected item in DropDownList ASP.NET MVC获取 DropDownList ASP.NET MVC 中的选定项
【发布时间】:2014-03-28 07:07:02
【问题描述】:

我知道关于如何获取 DropDownList 的选定值有多个线程。但是我找不到从控制器的局部视图中获取此值的正确方法。

这是我的部分观点:

@model List<aptest.Models.answer>

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

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 razor selecteditem html.dropdownlistfor


    【解决方案1】:

    为了获得下拉值,请将您的选择列表包装在一个表单标签中。使用模型和DropDownListFor helper

    剃刀视图

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

    控制器和其他类

    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
    }
    

    如果您使用局部视图,只需将模型传入其中:

    @Html.Partial("MyPartialView", Model)
    

    【讨论】:

    • 他想从局部视图而不是普通视图中获取价值!!
    • @Neel 没关系。
    • 你说的没关系是什么意思?
    • @Neel 在部分视图渲染后,下拉菜单是否在部分视图内并不重要。只要它在表单标签下渲染,它的值就会发布到服务器并且可以访问在 FormCollection 或 Request 对象中。
    • 非常感谢,它正在工作!该死的,我不知道我怎么能挣扎得这么厉害..
    【解决方案2】:
    ViewData["list"] = myList.ToList(); 
    

    剃须刀

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

    控制器

    public ActionResult ActionName(String ddl)
    {
    
      // now ddl has your dropdownlist's selected value i.e Id
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多