【问题标题】:How to get the value of a html dropdown list in MVC 4如何在 MVC 4 中获取 html 下拉列表的值
【发布时间】:2013-05-08 11:02:39
【问题描述】:

我是 MVC 新手,我正在为我的应用程序创建一个注册表单,我想添加一个下拉列表,我编写了如下所示的 HTML 下拉列表

                <select id="drpType">
                    <option value="0">Single</option>
                    <option value="1">Married</option>
                </select>

我想获得选定的值,我该如何实现,以及如何在 MVC 中为上述场景创建默认的@Html.DropDownList

【问题讨论】:

标签: c# asp.net-mvc-4


【解决方案1】:

你应该给你的下拉菜单一个名字(id不是必须的):

<select id="drpType" name="drpType">
    <option value="0">Single</option>
    <option value="1">Married</option>
</select>

然后在表单提交到的相应控制器操作中,您可以有一个同名的参数,该参数将包含所选值:

[HttpPost]
public ActionResult SomeAction(string drpType)
{
    // ... drpType will contain the selected value (0 or 1)
}

但实现这一点的正确方法是使用视图模型:

public class MyViewModel
{
    [Display(Name = "Marital status")]
    public string SelectedMaritalStatus { get; set; }

    public IEnumerable<SelectListItem> MaritalStatuses
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "0", Text = "Single" },
                new SelectListItem { Value = "1", Text = "Married" },
            };
        }
    }
}

然后您可以拥有一个具有 2 个操作的控制器(一个用于呈现表单,一个用于处理结果):

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // ... model.SelectedMaritalStatus will contain the selected value (0 or 1)
    }
}

现在您可以拥有一个强类型视图,您可以在其中使用 DropDownListFor 帮助器:

@model MyViewModel
@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.SelectedMaritalStatus)
        @Html.DropDownListFor(x => x.SelectedMaritalStatus, Model.MaritalStatuses)
    </div>
    <button type="submit">OK</button>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多