【问题标题】:Getting Select Option Value from Controller : ASP.NET MVC从控制器获取选择选项值:ASP.NET MVC
【发布时间】:2021-05-09 09:25:33
【问题描述】:

这是查看部分中的代码:

<select name="country">
    <option value="0">Select</option>
    @foreach (var country in countries)
    {
        <option value="@country.CountryId"> @country.CountryName</option>
    }
 </select>

从控制器获取值的代码:

public ActionResult IndexPost()
{
    ViewBag.Countries = CountryRepository.GetCountries();

    if (Request["btnSubmitCountry"] != null)
    {
        string country = Request["country"];
        ViewBag.Msg = "You have selected " + country;
    }
    return View();
   

我也想请求获取国家/地区名称的值,但现在它只获取 id。你能帮我用这个方法获取id和name吗?

【问题讨论】:

    标签: c# html .net asp.net-mvc


    【解决方案1】:

    因为select返回的是value的值,但是可以使用隐藏标签来存储文本值。

    例如:

      <form onsubmit="var sel=document.getElementById('country');document.getElementById('country_text').value=sel.options[sel.selectedIndex].text;">
        <select name="country" id="country">
                <option value="0">Select</option>
                @foreach (var country in countries)
                {
                    <option value="@country.CountryId"> @country.CountryName</option>
                }
        </select>
        <input type="hidden" name="country_text" id="country_text" />
      </form>
    

    获取文本:

    string countryText = Request["country_text"];
    

    【讨论】:

    • 它使用 JS 工作,有什么方法可以在不使用 JS 的情况下从选择选项中获取该文本值?另外,感谢您提供上述解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 2014-02-13
    • 2011-11-04
    相关资源
    最近更新 更多