如何在控制器中获取所选的下拉值和文本 [英] how to get the selected drop down value and text in controler

查看:80
本文介绍了如何在控制器中获取所选的下拉值和文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉列表我能够在控制器中获取所选的id值,但是如何获得所选的值



例子

从下拉列表我得到国家名称印度的id 1

如何获得id = 1和contryname = ndia in controler



only id am获取

解决方案

该名称未包含在任何表单提交中,因此如果您使用表单提交值,则需要使用该名称提交的id(例如,执行数据库查找),或者在页面上设置一些javascript,用于在隐藏字段中设置所选项目的名称,然后在模型中读取或绑定到数据。



使用提交的ID在服务器代码中查找名称是更好的解决方案。


你可以这样做



 @ using(Html.BeginForm(new {id =cf}))
{
< div >
< table width = 100% cellpadding = 0 cellspacing = 0 >
< tr >
< td > < < span class =code-leadattribute> b > 选择地区:< / b >
< td > < < span class =code-leadattribute> input type = hiden name = countryname id = hdnCountryName / > < / td >
< / td >
< td > @Html.DropDownListFor(m => m.countryId,ViewData [countries]为IEnumerable < SelectListItem > ,选择一个)< / td >
< / tr < span class =code-keyword>>


< /表格 >
< / div >
}





c#

  public  ActionResult GetCountry( string  countryname, string  countryid)
{
// 执行操作

return 查看();
}





javascript

 < script     type   =  text / javascript >  


< blockquote>(' #countryId')。on(' 更改',功能( event ){
var form =


i have a dropdownlist i am able to get the selected id value in controller but how to get the selected value

example
from dropdown i am getting id 1 for country name india
how to get id=1 and contryname=ndia in controler

only id am getting

解决方案

The name isn't included in any form submission so if you are using a form to submit the value you'll need to either work the name out from the id that was submitted (do a database lookup for example), or have some javascript on the page that sets the name of the selected item in a hidden field that you then read in your model, or data bind to.

Looking the name up in your server code using the submitted id is the better solution though.


You can do it this way

@using (Html.BeginForm( new {id="cf"}))
{
<div>
    <table width="100%" cellpadding="0" cellspacing="0">
        <tr>
            <td><b>Select a District:</b>
<td><input type="hiden" name="countryname" id="hdnCountryName" /> </td>
</td>
            <td>@Html.DropDownListFor(m => m.countryId, ViewData["countries"] as IEnumerable<SelectListItem>, "Select One")</td>
        </tr>
      
    </table>
</div>
}



c#

public ActionResult GetCountry( string countryname, string countryid)
  {
     //do action

      return View();
  }



javascript

<script type="text/javascript">


('#countryId').on('change', function(event){ var form =


这篇关于如何在控制器中获取所选的下拉值和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆