【问题标题】:How to pass value of selected dropdownlist from view to the controller如何将选定下拉列表的值从视图传递到控制器
【发布时间】:2014-10-23 16:19:23
【问题描述】:

我的视图中有一个下拉菜单、几个其他控件和一个用于保存数据的输入按钮。 保存时我有 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
    }

【问题讨论】:

    标签: c# model-view-controller


    【解决方案1】:

    向模型添加一个属性来存储值。我假设 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() 没有任何参数。为了能够读取发布的数据,您需要将模型作为参数。因此,如果它被称为 MyModel,您的控制器方法的签名将是:

    public ActionResult Save(MyModel model)
    

    然后将值分配给您想要的变量就是:

    int DocumentType = model.DocumentTypeId;
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

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