绑定下拉选择值到MVC2中的Label

时间:2010-11-17 04:14:07

标签: asp.net-mvc asp.net-mvc-2

我是VS 2010和MVC2的新用户。我已经从数据库填充了一个下拉列表。我的HomeControler源代码将是 ` 命名空间SampleControls.Controllers {

public class HomeController : Controller
{
    SControlsDataContext data = new SControlsDataContext();

    public ActionResult Index()
     {
         var Emp = from prod in data.Emps
                   select prod;
         ViewData["Emps"] = Emp;
         return View();
     }      

    public ActionResult About()
    {
        return View();
    }

}

} `

我的Index.aspx将是

<% using (Html.BeginForm()) { %> <%= Html.DropDownList("lstProducts", new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), new { onChange = "onSelectedIndexChanged()" })%> <% } %>

我想要的是“在SelectedIndexChanged上,所选的值应该显示在标签中。

 <script type="text/javascript">
    function onSelectedIndexChanged() 
      {
       //i know i should write the code here for binding the dropdown selected value to label... But, i dont know how to do this.
      }
</script> 

1 个答案:

答案 0 :(得分:2)

<% using (Html.BeginForm()) { %> 
    <%= Html.DropDownList("lstProducts", 
        new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), 
        new { onchange = "onSelectedIndexChanged(this.value)" })%> 
<% } %>

<div id="foo"></div>

然后:

function onSelectedIndexChanged(value) {
    document.getElementById('foo').innerHTML = value;
}

更新:

为了获得所选文字:

<% using (Html.BeginForm()) { %> 
    <%= Html.DropDownList("lstProducts", 
        new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), 
        new { onchange = "onSelectedIndexChanged(this)" })%> 
<% } %>

function onSelectedIndexChanged(select) {
    var text = select.options[select.selectedIndex].text;
    document.getElementById('foo').innerHTML = text;
}

更新2:

使用jquery可以实现同样的目的:

<% using (Html.BeginForm()) { %> 
    <%= Html.DropDownList("lstProducts", 
        new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), 
        new { id="myselect" })%> 
<% } %>

然后:

$(function() {
    $('#myselect').change(function() {
        var text = $(this).find('option:selected').text();
        $('#foo').html(text);
    });
});