如何在 MVC 控制器中获取 DropDownList 选定的文本

How to get DropDownList selected Text in MVC controller

我在 html 中有这个 DropDownList,我可以在其中 select Texts.Text = 项目,值 = ID

 @Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control" })

单击控制器中的提交按钮后,我可以看到值 (ID) 已传递并 post 返回到数据库。我希望文本 post 进入数据库。

控制器端代码行:

detailsConfig.Project = Convert.ToString(form["Project"]);

例如: 如果下拉列表值为

Project     ID
test        1
testagain   2

我应该在控制器中进行测试,而不是 1。请帮助

您使用该下拉更改事件并将该名称存储在隐藏字段中并将该值获取到控制器。

查看:-

@Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control",@id="ddlProject" })

<input type="hidden" id = "hdnProjectName" name="ProjectName" />

Jquery:-

$("#ddlProject").on("change", function () {
              $("#hdnProjectName").val($(this).find("option:selected").text());
        });

控制器:-

public ActionResult Save(FormCollection formcollection)
{
   var projectName = formcollection["ProjectName"];
 }

首先,您绝对应该将下拉列表强类型化为您的模型。

我的意思是这个...

在控制器中,我将创建要在视图中使用的 select列表。


控制器

ViewBag.ProjectSelection = new SelectList(/* your data source */, "Project", "Project");

Disclaimer:

Submitting the Text value is not preferred because typically the Text value of the select element is not unique. Submitting the ID to the server is the best practice.. and then you can simply query the database based on the ID you submitted to get the values you want. This is the best way to get the most accurate and reliable data.


然后在您看来,将您的 ProjectSelection select 列表强类型输入到您模型中的 Project 属性。

查看

@Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewBag.ProjectSelection, "-- Select LineID --", new { required = true, @class = "form-control" })

为什么要在下拉列表中声明 required?那应该在你的模型中声明.


说明

在 MVC 中,当涉及到 HTML 元素时,用户可以在其中 select 将选项提交给服务器(下拉列表、列表框等) ).. 只会提交 Value(在您的情况下是 ID)。元素的 Text 部分仅供用户查看,以使他们的 selection 更容易。


如果有帮助请告诉我!

new SelectList(Model.dropConfig, "Project", "Project")

以上更改解决了我的问题。谢谢@StephenMuecke :)