【问题标题】:How Do I Get ID From Item In DropDownList?如何从 DropDownList 中的项目获取 ID?
【发布时间】:2015-09-24 14:05:50
【问题描述】:

这是我上一个帖子的后续:How Do I Create A HTML Select With Only Items In Database In Asp.Net Razor?

如何从 DropDownList 中选择的项目中获取 ID?这个想法是下拉列表中显示的名称连接到“CustomerId”。

http://i.imgur.com/2756GKl.png

PS 我不想用最后一个线程中的所有代码填充这个线程,因为它会变得非常混乱和混乱,所以如果你需要查看这段代码的参考,请看在另一个线程。

HTML 代码

@Html.LabelFor(m => m.SelectedCustomerId)
@Html.DropDownListFor(m => m.SelectedCustomerId, Model.CustomerID)

注册控制器

[HttpPost]
public ActionResult Register(string registername, string registerpassword, string registerconfirmpassword, int customerId)
{
    if (ModelState.IsValid)
    {     
    this.customerId = Request["CustomerID"]);

    //Register new user with this information
    //Removed for clarity
    return Redirect("/");
}

【问题讨论】:

  • 使用模型作为方法参数而不是许多字符串参数,并使用该模型而不是Request["key"]
  • 我会看看改变它:)

标签: c# html asp.net razor


【解决方案1】:

再看看你是如何定义下拉列表的:

@Html.DropDownListFor(m => m.SelectedCustomerId

这将大致呈现为:

<select name="SelectedCustomerId" id="SelectedCustomerId"

所以下拉列表的值将被回复为SelectedCustomerId=5(或选择的任何值)。因此,要捕获它,您需要使用相同的名称声明您的参数(不区分大小写的 afaik):

[HttpPost]
public ActionResult Register(..., int selectedCustomerId)

但是,还有另一种可以说更好的方法。请注意,您的操作中已经有 4 个参数。这已经不是很可读了。这里更好的方法是定义一个模型类,或者重用你已经用来渲染视图的模型类,并使其成为你操作的唯一参数。然后只需使用它的属性,因为它们将由模型绑定器填充:

[HttpPost]
public ActionResult Register(TheModelType model)
{
    model.SelectedCustomerId // to access the selected customer id

【讨论】:

  • 我首先尝试了模型解决方案。它使我对已使用的密钥产生了一些错误。因此,我尝试了“int selectedCustomerId”解决方案,并且效果很好。谢谢,标记为答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
相关资源
最近更新 更多