如何将所选下拉列表的值从视图传递到控制器

本文关键字:视图 控制器 下拉列表 | 更新日期: 2023-09-27 18:27:46

我的视图中有一个下拉列表、几个其他控件和一个用于保存数据的输入按钮。保存时,我有ActionReult Save()它需要我在下拉列表中选择的值。如何获取控制器上下拉列表的选定值Actionresult Save()

View:
------
Collapse | Copy Code
var docTypes = Model.DocumentTypes.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString()}).AsEnumerable();
@Html.DropDownList("SelectedDocumentType", docTypes, "--select--", new { @class = "ddSelect" })
Model:
-----
Collapse | Copy Code
public IEnumerable DocumentTypes { get; set; }
   Controller:
   -----------
   Collapse | Copy Code
   [HttpParamAction]
   [HttpPost]
   [ValidateInput(false)]
       public ActionResult Save()
 {
   int DocumentType = // I have to assign the selected value of the dropdownlist here
    }

如何将所选下拉列表的值从视图传递到控制器

将属性添加到模型中以存储值。我假设id是int,不需要像现在这样使用ToString()

public int DocumentTypeId {get;set;}

然后,您应该使用HtmlHelper方法将下拉列表绑定到值DropDownListFor。这给了你:

@Html.DropDownListFor(model => model.DocumentTypeId, new SelectList(Model.DocumentTypes, "Id", "Name"), "--select--", new { @class = "ddSelect" })

并且您可以删除docTypes变量的创建和初始化。

编辑:我注意到的另一个问题是,您的控制器方法Save()没有任何参数。为了能够读取POSTed数据,您需要将模型作为参数。因此,如果它被称为MyModel,您的控制器方法的签名将是:

public ActionResult Save(MyModel model)

然后将值分配给您想要的变量,只需:

int DocumentType = model.DocumentTypeId;

尝试使用int.Parse(drop.SelectedValue)int.Parse(drop.SelectedValue.Trim())而不是Int32.Parse(drop.SelectedValue.ToString())。滴SelectedValue已经是字符串格式,因此不需要使用ToString 进行转换