【问题标题】:How to send dropdown selected item text to controller in ASP.NET MVC?如何将下拉选定项文本发送到 ASP.NET MVC 中的控制器?
【发布时间】:2023-04-10 11:51:01
【问题描述】:

我需要将选定的下拉项文本而不是值发送到控制器。 这是查看代码

 @using (Html.BeginForm("Index", "Home"))
      {
      <div class="container">
          <div class="form-group">
              @if (ViewBag.CountryList != null)
              {
                  @Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "choose country", new { @class = "form-control" })
              }
          </div>
          <button type="submit">Send</button>
      </div>
      }

在控制器中,我尝试访问提交表单的请求上下文,但它返回的是值,而不是所选项目的文本。请帮助将所选下拉项的文本检索到控制器。

【问题讨论】:

    标签: c# .net asp.net-mvc model-view-controller


    【解决方案1】:

    您可以从 ViewBag 的 Value 属性传递 IdValue 字段 试试这个:

    @Html.DropDownListFor(x => x.CountryId, new SelectList(@ViewBag.CountryList, "Value", "Value"), new { @class = "form-control" })
    

    【讨论】:

      【解决方案2】:

      只需传递您的模型(将 YourModel 替换为您的模型

      [HttpPost]
      public ActionResult Index(YourModel objModel)
      {
          var CountryId = objModel.CountryId
      }
      

      【讨论】:

      • 我试过了,但它会发送选项标签的值属性值,而不是开始和结束标签之间的文本。找到了使用 Jquery ``` ``` 但是太复杂了。请建议其他解决方案。
      • @P3ar1baron 分享您的 ViewBag.CountryList 代码
      • 这里是 List CountryList = db.Countries.ToList(); ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
      • 试试这个 ViewBag.CountryList = new SelectList(CountryList, "CountryName", "CountryName");和@Html.DropDownListFor(x => x.CountryName, new SelectList(@ViewBag.CountryList, "CountryName", "CountryName"), new { @class= "form-control" })
      猜你喜欢
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 2014-10-16
      相关资源
      最近更新 更多