从控制器获取选择选项值:ASP.NET MVC

时间:2021-02-05 01:45:14

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

这是查看部分的代码:

<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 吗?

1 个答案:

答案 0 :(得分:0)

因为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"];
相关问题