如何从下拉列表中填充表单值?

Sha*_*ica 1 razor asp.net-mvc-3

此问题的后续操作:如果我想根据用户从下拉列表中选择的值来计算值,并将该值放入表单变量/模型属性中,我该如何操作?

Dar*_*rov 5

真的,如果我有一个建议给任何ASP.NET MVC开发人员:使用视图模型而忘记ViewBag/ViewData.在99%的案例中,这是他的问题/问题的解决方案.

所以这里的最小视图模型将允许您正确表示下拉列表:

public class MyViewModel
{
    // a scalar property on the view model to hold the selected value
    [DisplayName("item")]
    [Required]
    public string ItemId { get; set; }

    // a collection to represent the list of available options
    // in the drop down
    public IEnumerable<SelectListItem> Items { get; set; }

    ... and some other properties that your view might require
}
Run Code Online (Sandbox Code Playgroud)

然后有一个控制器动作,它将填充并将此视图模型传递给视图:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        // TODO: those values probably come from your database or something
        Items = new[]
        {
            new SelectListItem { Value = "1", Text = "item 1" },
            new SelectListItem { Value = "2", Text = "item 2" },
            new SelectListItem { Value = "3", Text = "item 3" },
        }
    };
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

那么你可以为这个视图模型提供一个相应的强类型视图,它可以包含一个表单和下拉列表:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.ItemId)
    @Html.DropDownListFor(x => x.ItemId, Model.Items, "--Select One--")
    <button type="submit">OK</button>
}
Run Code Online (Sandbox Code Playgroud)

最后,您可以在控制器上对此表单进行相应的操作,并在其中您可以从下拉列表中检索所选值:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    // model.ItemId will contain the selected value from the dropdown list
    ...
}
Run Code Online (Sandbox Code Playgroud)